为什么推送到 "r" 数组在循环中无法正常工作?

Why the push to "r" array not working properly in the loop?

为什么以下数组在循环中没有正确推送到 r?

如果我改为 if((pivot + originArr[c]) <= 5) 而不是 if((pivot + originArr[c]) <= 3)

我的结果是错误的:

[ [ 0, 1, 2, 3, 4 ],
  [ 0, 1, 2, 3, 4 ],
  [ 0, 1, 2, 3, 4 ],
  [ 0, 2, 3 ],
  [ 1, 2, 3 ] ]

预期结果应该是[ [ 0, 1, 2], [ 0, 1, 3], [ 0, 1, 4], [ 0, 2, 3 ] ]

如果r不为空,则递归将第一次迭代结果送入函数计算,直到r为空。对于每个 c 循环,它不会将单独的数组组推送到“r”。

var data = [0, 1, 2, 3, 4, 5];

function compute(originArr, filterArr) {
  var r = [];
  var arr;

  let firstLoop = false;
  if (filterArr.length == 0) {
    firstLoop = true;
    arr = originArr;
  } else {
    arr = filterArr;
  }

  arr.forEach(function(i, index) {
    
    var pivot;
    if (firstLoop) {
      pivot = index;
    } else {
      pivot = parseInt(i.slice(-1));
    }
    var nextIndex = pivot + 1;
    console.log(pivot, nextIndex);
    for (var c = nextIndex; c < originArr.length; c++) {
      let tempResult = [];
      console.log(c);
      if (pivot + originArr[c] <= 3) {
        if (firstLoop) {
          tempResult.push(index);
        } else {
          tempResult = i;
        }
        tempResult.push(c);
        console.log(tempResult);
        r.push(tempResult); // suppose to push [0,1], [0,2], [0,3], [1,2] for the first iteration
      }
    }
  });

  if (r.length > 0) {
    return compute(originArr, r);
  } else {
    return arr;
  }
}

console.log(compute(data, []));
//Final result should be [[0,1,2]]

我想我发现了问题。

我们不能像这样克隆数组

tempResult = i;

在我将新数字推送到 temResult 后,它会影响引用 'i'。

所以我的解决办法是把克隆方式改成:

tempResult = [...i];

克隆不会影响引用。