简体   繁体   中英

Javascript push array into another array

Is there any difference between the following code(with/without spread operator)?

let result = [];
let arr1 = [1,2,3];

result.push(arr1)
result.push([...arr1])

In the first, without spreading, any modifications to the array at the 0th position in result will result in a change to the original arr1 as well, and vice versa.

If you spread the array while pushing, though, such changes will not occur; the two arrays (one in arr1 , one in result[0] ) will be completely independent.

 let result = []; let arr1 = [1,2,3]; result.push(arr1) arr1[1] = 999; console.log(result);

 let result = []; let arr1 = [1,2,3]; result.push([...arr1]) arr1[1] = 999; console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM