在本地修改数组变量时,我需要保存一个副本。由于某些原因,下面的代码似乎无法做到这一点。
var tileArray;
.
.
.
function simplify (tiles){
tileArray = tiles; //tileArray is the global variable passed to simplify()
for (var i = 0; i < tiles.length; i++){
if (tiles[i].numeratorDim == ""){tiles[i].numeratorDim = 1};
if (tiles[i].denominatorDim == ""){tiles[i].denominatorDim = 1};
};
while (thereIsAMatch(tiles)){ // a bunch of code modifying tiles, but not tileArray
for (var i = 0; i < tiles.length; i++){
for (var j = 0; j < tiles.length; j ++) {
if (unitsMatch(tiles[i].numeratorUnit, tiles[j].denominatorUnit)) {
tiles[i].numeratorDim = parseInt(tiles[i].numeratorDim) - 1;
if (tiles[i].numeratorDim == 0){tiles[i].numeratorUnit = ""}
tiles[j].denominatorDim = parseInt(tiles[j].denominatorDim) - 1;
if (tiles[j].denominatorDim == 0){tiles[j].denominatorUnit = ""}
} // if unitsMatch
} // for j
} //for i
} //while thereIsAMatch
console.log(tileArray === tiles); //returns TRUE!! But tileArray hasnt been modified!!
return tiles;
} // function simplify
答案 0 :(得分:0)
您需要对此数组进行深层复制,因为现在tile和tileArray指向同一块内存(引用)。您可以使用tileArray = Arrays.from(tiles)
这是一篇很有帮助的文章:https://medium.com/@gamshan001/javascript-deep-copy-for-array-and-object-97e3d4bc401a
答案 1 :(得分:-1)
基本上,tileArray引用相同的数组,而不是为此创建副本,
使用:
tileArray = tiles.slice()
slice(),该操作会克隆数组并返回引用
答案 2 :(得分:-1)