具有不同回调的同一函数的不同输出(堆算法)



我正在使用堆算法,它与回调函数output控制台记录结果一起工作得很好。但是如果我把回调函数output的动作改为array.push,它就会一次又一次地推同一个数组。我做错了什么?

let swap = function (array, index1, index2) {
var temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
return array;
};
let permutationHeap = function (array, callback, n) {
n = n || array.length;
if (n === 1) {
callback(array);
} else {
for (var i = 1; i <= n; i++) {
permutationHeap(array, callback, n - 1);
if (n % 2) {
swap(array, 0, n - 1);
} else {
swap(array, i - 1, n - 1);
}
}
}
};
let finalResult = [];
var output = function (input) {
//console.log(input);
finalResult.push(input);
};
permutationHeap(["Mary", "John", "Denis"], output);

console.log(finalResult)

数组是Object,对象是指针/引用。我使用spread操作符来克隆输入,所以它不会继续做参考jitsu

let swap = function (array, index1, index2) {
var temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
return array;
};
let permutationHeap = function (array, callback, n) {
n = n || array.length;
if (n === 1) {
callback(array);
} else {
for (var i = 1; i <= n; i++) {
permutationHeap(array, callback, n - 1);
if (n % 2) {
swap(array, 0, n - 1);
} else {
swap(array, i - 1, n - 1);
}
}
}
};
let finalResult = [];
var output = function (input) {
//console.log(input);
finalResult.push([...input]); //spread operator >:D
};
permutationHeap(["Mary", "John", "Denis"], output);

console.log(finalResult)

最新更新