Unexpected value change in 2D array in JavaScript -


i'm trying modify 1 value in 2d array. i'm finding weird behavior based on how array constructed.

the difference between matrix , matrix2 how they're constructed. when change [1][1] value, of [x][1] values in matrix2 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 explain what's going on?

[row, row, row] 

you made array 3 references the same inner array.

changes inner array can seen through reference it.

you want create 3 copies of inner array.
can create shallow copy of array calling .slice().


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -