javascript - 为什么修改 array.slice() 也会改变原始数组?

标签 javascript arrays node.js

我正在尝试修改复制的数组而不更改原始数组。这是我尝试过的方法,使用 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 保持不变。谢谢

最佳答案

Slice MDN 所示, slice 方法返回调用它的数组的浅拷贝。 Deep copy讨论了在 JS 中深度复制对象的几种方法。它提到的一个很好的是

var secondArr = JSON.parse(JSON.stringify(mainArr))

这会将您的数组转换为 JSON,然后将其解析为一个新对象

关于javascript - 为什么修改 array.slice() 也会改变原始数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55015153/

相关文章:

arrays - 如何将数组传递给 bash shell 脚本?

.net - 替换 for...if 数组迭代

mysql - 当数据库更改时,socket.io 中的值不会更新

javascript - 获取房间内的用户数量

javascript - 如何阻止 Keyup 事件触发两次

javascript - jQuery - 替换 MyBB 消息但不是其中的一部分

c++ - while循环继续运行

node.js - 在Docker中使用负载测试应用

javascript - 循环遍历数组中的对象并向每个对象添加属性

Javascript/jQuery : SCRIPT438 error with IE7/8, 有什么调试技巧吗?