What am I missing with the understanding of Arrays?
当数组被分配给另一个变量时,将传递引用,而不是传递值。当您使用
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 |
在上面的输入中,当我修改数组
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]] |
但当我做下面的工作时,它会变异成
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]] |
为什么会这样?这种行为发生在使用数组方法来改变数组时。
1 | var c = [].concat(a); |
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.