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



为什么下面的数组在循环中没有正确地推送到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〃;是空的。它不会将数组的单个组推到"0";r〃;对于每个c循环。

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];

该克隆不会影响引用。

最新更新