0

我正在使用堆算法,它与output记录结果的回调函数控制台配合得很好。但是,如果我将回调函数的操作更改outputarray.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)

4

1 回答 1

1

数组是一个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)

于 2021-02-26T22:36:19.790 回答