Assigning JSON array as variable in JavaScript

In JavaScript, if you assign a JSON array to another variable, you are actually assigning the reference (address) of the array to the new variable, rather than copying the entire array. This means that the new variable and the original array are actually the same array object, and their contents will affect each other. When you modify the elements in one array, the corresponding elements in the other array will also change, because they actually are the same element.

1. If you modify the elements in the original array, the corresponding elements in the new variable will also change:

let a = [1, 2, 3];
let b = a;  // 把 a 的引用赋值给 b

a[0] = 0;
console.log(b);  // 输出 [0, 2, 3]

2. If you add or delete elements to the new variable, the original array will also change accordingly:

let a = [1, 2, 3];
let b = a;  // 把 a 的引用赋值给 b

b.push(4);
console.log(a);  // 输出 [1, 2, 3, 4]

3. If you want to copy an array instead of sharing a reference, you can use the [slice()] method or the spread operator […]:

let a = [1, 2, 3];
let b = a.slice();  // 复制 a 并赋值给 b

a[0] = 0;
console.log(a);  // 输出 [0, 2, 3]
console.log(b);  // 输出 [1, 2, 3]


let a = [1, 2, 3];
let b = [...a];  // 复制 a 并赋值给 b

a.push(4);
console.log(a);  // 输出 [1, 2, 3, 4]
console.log(b);  // 输出 [1, 2, 3]

In this way, the new array and the original array are two independent array objects, and their contents no longer affect each other.

Guess you like

Origin blog.csdn.net/weixin_44380380/article/details/130090068