简体   繁体   中英

Unexpected value change in 2D array in JavaScript

I'm trying to modify one value in a 2D array. 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. However when I change the [1][1] value, all of the [x][1] values in matrix2 are changed:

Matrix:

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

Matrix2 (unexpected):

[ [ 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() .

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