我试图在不更改原始数组的情况下修改复制的数组。这是我通过使用slice()
方法尝试过的方法,但未按预期工作:
//toFill holds the values I want to add into an array named secondArr,
//replace every empty sting within secondArr with 0
var toFill = [0, 0, 0, 0];
var mainArr = [
[" ", 1, 1, 1],
[" ", 1, 1, 1],
[" ", 1, 1, 1],
[" ", 1, 1, 1]
];
var secondArr = mainArr.slice(0,4);
//this function returns a 1D array, stores the indices of all empty strings within an array
function findBlankSpaces(secondArr) {
var emptyIndices = [];
var innerArrLen = secondArr.length;
var outterArrLen = secondArr[0].length;
for (var i = 0; i < innerArrLen; i++) {
for (var j = 0; j < outterArrLen; j++) {
if (secondArr[i][j] == " ") {
emptyIndices.push([i, j]);
}
}
}
return emptyIndices;
}
//this function returns the modified array, with empty spaces replaced with 0s
function fillWithZero(secondArr, toFill) {
var emptyIndices = findBlankSpaces(secondArr);
for (var i = 0; i < emptyIndices.length; i++) {
secondArr[emptyIndices[i][0]][emptyIndices[i][1]] = toFill[i];
}
}
//consoles
console.log(fillWithZero(secondArr, toFill));
console.log(mainArr);
//expected output in console is [[" ", 1,1,1], [" ",1,1,1], [" ",1,1,1], [" ",1,1,1]];
//actual output is [[0,1,1,1], [0,1,1,1], [0,1,1,1], [0,1,1,1]];
//I didn't modify mainArr, but only modified secondArr, why that mainArr also affected?
我没有修改 mainArr ,仅使用
slice()
创建了一个副本,但是为什么当它的副本更改时它会不断更改?这个问题是:任何阻止这种情况发生的方法,或者我如何再次调用 mainArr 而没有任何0,我希望 mainArr 保持不变。谢谢
最佳答案
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
此处的关键字是shallow
。mainArr
是一个数组数组,因此slice
将为您提供外部数组的新副本,但它为您提供的数组包含对mainArray
中各项的引用,因此,在修改它们时,您实际上是在修改mainArray
中的各项。
您可以深度克隆mainArr,但是仅替换所需的位可能会更有效率。
尽管可以将其做得更干净,但仍可行。一种选择是使用immer进行修改。
//replace every empty sting within secondArr with 0
var toFill = [0, 0, 0, 0];
var mainArr = [[" ", 1, 1, 1], [" ", 1, 1, 1], [" ", 1, 1, 1], [" ", 1, 1, 1]];
//this function returns a 1D array, stores the indices of all empty strings within an array
function findBlankSpaces(arr) {
var emptyIndices = [];
var innerArrLen = arr.length;
var outterArrLen = arr[0].length;
for (var i = 0; i < innerArrLen; i++) {
for (var j = 0; j < outterArrLen; j++) {
if (arr[i][j] == " ") {
emptyIndices.push([i, j]);
}
}
}
return emptyIndices;
}
//this function returns the modified array, with empty spaces replaced with 0s
function fillWithZero(mainArr, toFill) {
var emptyIndices = findBlankSpaces(mainArr);
let newArr = [...mainArr];
emptyIndices.forEach(indic => {
newArr[indic[0]] = [
...mainArr[indic[0]].slice(0, indic[1]),
toFill[indic[1]],
...mainArr[indic[0]].slice(indic[1] + 1)
];
});
return newArr;
}
//consoles
console.log(fillWithZero(mainArr, toFill));
console.log(mainArr);