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

Different outputs for the same function with different callbacks (Heap's Algorithm)

我正在使用堆算法,它与回调函数 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,对象是 pointers/references..我使用 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)