js uses = to assign the array directly, and the problem that the original array is modified when the new array is modified is solved (deep copy)

Use = to assign the array directly, the original array will be modified when the new array is modified:

let oldArr = [
    {group: 1, id: 2, name: "aa"},
    {group: 2, id: 1, name: "bb"}];
let newArr2 = oldArr;
for (let i = 0; i < newArr2.length; i++) {
    if (newArr2[i].id == 1) {
        newArr2[i].name = "new";
        break;
    }
}
console.log(oldArr);
console.log(newArr2);

 

Using object deep copy, modifying the array does not affect the original array:

let oldArr = [
    {group: 1, id: 2, name: "aa"},
    {group: 2, id: 1, name: "bb"}];


let newArr2 = JSON.parse(JSON.stringify(oldArr)); //对象深拷贝,修改不影响之前的
for (let i = 0; i < newArr2.length; i++) {
    if (newArr2[i].id == 1) {
        newArr2[i].name = "new";
        break;
    }
}
console.log(oldArr);
console.log(newArr2);

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_40015157/article/details/113869061