简体   繁体   English

JavaScript中的2D数组中出现意外的值更改

[英]Unexpected value change in 2D array in JavaScript

I'm trying to modify one value in a 2D array. 我正在尝试修改2D数组中的一个值。 However I'm finding some weird behavior based on how the array is constructed. 但是我发现了一些奇怪的行为,基于数组的构造方式。

The only difference between matrix and matrix2 is how they're constructed. 矩阵和矩阵2之间的唯一区别在于它们是如何构造的。 However when I change the [1][1] value, all of the [x][1] values in matrix2 are changed: 但是,当我更改[1] [1]值时,矩阵2中的所有[x] [1]值都会更改:

Matrix: 矩阵:

[ [ 0, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 0 ] ]

Matrix2 (unexpected): Matrix2(意外):

[ [ 0, 1, 0 ], [ 0, 1, 0 ], [ 0, 1, 0 ] ]

Code: 码:

var row = [0,0,0];
var matrix = [[0,0,0],[0,0,0],[0,0,0]];
var matrix2 = [row, row, row];
console.log(matrix);
console.log(matrix2);
matrix[1][1] = 1;
matrix2[1][1] = 1;
console.log(matrix);
console.log(matrix2);

Can anyone explain what's going on? 谁能解释一下发生了什么?

[row, row, row]

You just made an array with three references to the same inner array. 您刚刚创建了一个包含对同一内部数组的三个引用数组。

Changes to the inner array can be seen through any reference to it. 通过对它的任何引用都可以看到对内部数组的更改。

You want to create three copies of the inner array. 您想要创建内部数组的三个副本。
You can create a shallow copy of an array by calling .slice() . 您可以通过调用.slice()来创建数组的浅表副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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