关于javascript:对于数组的理解我缺少什么?

What am I missing with the understanding of Arrays?

当数组被分配给另一个变量时,将传递引用,而不是传递值。当您使用==运算符比较两个数组并返回true时,确认了这一点。

1
2
3
4
5
6
var a = [[1,2],[3,4],[5,6]];
var b = a; // b = [[1,2],[3,4],[5,6]]
var c = [].concat(a); // c = [[1,2],[3,4],[5,6]]

a == b; //true
a == c; //false

在上面的输入中,当我修改数组b时,它会改变数组a,而不是c

1
2
3
b.push([7,8]); // b = [[1,2],[3,4],[5,6], [7,8]]
a; //a = [[1,2],[3,4],[5,6], [7,8]]
c; //c = [[1,2],[3,4],[5,6]]

但当我做下面的工作时,它会变异成c

1
2
3
b[0].push(5); // b = [[1,2,5],[3,4],[5,6], [7,8]]
a; //a = [[1,2,5],[3,4],[5,6], [7,8]]
c; //c = [[1,2,5],[3,4],[5,6]]

为什么会这样?这种行为发生在使用数组方法来改变数组时。


.concat()做了一个浅显的复制。所以在排队之后:

1
var c = [].concat(a);

ca引用不同的数组,但c[0]b[0]a[0]都引用相同的数组。

MDN报价:

concat copies object references into the new array. Both the original and new array refer to the same object. That is, if a referenced object is modified, the changes are visible to both the new and original arrays.