[英]Creating new array with updating array element without mutating the original array
This is the array and I want to replace the elements "A" and "B" with "D".这是数组,我想用“D”替换元素“A”和“B”。 I don't want to mutate the original array, So I have used spread operator.
我不想改变原始数组,所以我使用了展开运算符。 But still my original array getting mutating whenever I will update the newArr.
但是每当我更新 newArr 时,我的原始数组仍然会发生变异。 I want originalArray should be
[["A", 2],["B",1]]
and newArr should be [["D", 2],["D",1]]
Can anyone suggest me the solution for this我希望 originalArray 应该是
[["A", 2],["B",1]]
并且 newArr 应该是[["D", 2],["D",1]]
谁能给我建议解决方案这个
let originalArray = [["A", 2],["B",1]];
let newArr = [ ...originalArray ];
for(let i=0;i<newArr.length;i++){
newArr[i][0] = "D";
}
console.log(originalArray )
console.log(newArr)
Spreading does not imply a deep copy.传播并不意味着深拷贝。 You have a two dimensional array so when you spread the top level, the nested arrays are still referencing the original array:
你有一个二维数组,所以当你展开顶层时,嵌套的 arrays 仍然引用原始数组:
let originalArray = [["A", 2], ["B",1]];
let newArr = [...originalArray];
console.log(originalArray[0] === newArr[0]) // true
the simplest change necessary is to also spread the nested array最简单的必要更改是也传播嵌套数组
let originalArray = [["A", 2], ["B",1]];
let newArr = [...originalArray];
for(let i = 0; i < newArr.length; i++) {
newArr[i] = ["D", ...newArr[i].slice(1)]; // make a copy here as well using slice and omitting the first element
}
console.log(originalArray )
console.log(newArr)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.