[英]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.首先,在不扩散的情况下,对
result
中第 0 个 position 的阵列的任何修改都将导致对原始arr1
的更改,反之亦然。
If you spread the array while pushing, though, such changes will not occur;但是,如果在 push 的同时展开数组,则不会发生这种变化; the two arrays (one in
arr1
, one in result[0]
) will be completely independent.两个 arrays (一个在
arr1
,一个在result[0]
)将完全独立。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.