简体   繁体   English

在不改变原始数组的情况下通过更新数组元素创建新数组

[英]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.

相关问题 Javascript 中的反向数组而不改变原始数组 - Reverse array in Javascript without mutating original array 过滤javascript树而不更改原始数组 - Filter a javascript tree without mutating the original array 一个 map 如何创建一个数组以创建一个具有更改数组项但不改变原始数组或其任何项的新数组? - How does one map an array in order to create both a new array with changed array items but without mutating the original array or any of its items? 如何在不更改原始数组的情况下过滤嵌套数组? - How can I filter a nested array without mutating the original array? 在不改变原始数组的情况下在数组中添加对象的算法 - algorithm to add up objects in an array without mutating the original array 如何在不改变原始数组的情况下对数组进行排序? - How can you sort an array without mutating the original array? 如何将数组传递给函数而不改变原始数组? - How to pass an array to a function without mutating the original array? 替换数组中特定位置的元素而不改变它 - Replace element at specific position in an array without mutating it 如何在对象的嵌套数组中添加对象而不改变原始源 - how to add object in nested array of objects without mutating original source 如何在不更改原始数组的情况下破坏对象属性? - How do i destruct object properties without mutating original array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM