Strange behavior when nesting 2D arrays in a 3D array

I am currently working on a Minimax four-in-line algorithm in javascript. I decided to save possible movements in the array, continuing the nest arrays inside the arrays for each branch.

However, when I try to edit a specific value in an array, it edits all other values ​​in a single column.

the code:

var BOARD = [
    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0]
    ];

// Put 3 x 2D Arrays into one 3D Array
var NODE_TREE = [BOARD, BOARD, BOARD];
NODE_TREE[1][2][0] = 2;
console.log(NODE_TREE);

Chrome V8 interpreter output:

[ [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 2, 0, 0 ] ],
  [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 2, 0, 0 ] ],
  [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 2, 0, 0 ] ] ]

What should happen, but dosen't:

[ [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ],
  [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 2, 0, 0 ] ],
  [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ] ]

Javascript seems to ignore the first index index. This problem only occurs when using an existing array nested in an array. If I were to create a 3D array from scratch, this error would not happen.

+4
source share
2

JSON.

.

var BOARD = [
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]
    ],
    JSON_BOARD = JSON.stringify(BOARD),
    NODE_TREE = [JSON.parse(JSON_BOARD), JSON.parse(JSON_BOARD), JSON.parse(JSON_BOARD)];

NODE_TREE[1][2][0] = 2;
console.log(NODE_TREE);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Hide result
+1

BOARD 3 , "" , 3 BOARD.

, , BOARD.

3 3D-, . Array.prototype.slice();

var BOARD = [
    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0]
    ];
    
// function to map and copy arrays with .slice()
function sliceArrays (outerArray){
  return outerArray.map((arr)=>{
    return arr.slice()
  });
}

var NODE_TREE = [sliceArrays(BOARD), sliceArrays(BOARD), sliceArrays(BOARD)];
NODE_TREE[1][2][0] = 2;
console.log(NODE_TREE);

//[ [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ],
//  [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 2, 0, 0 ] ],
//  [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ] ]
Hide result
+1
source

Source: https://habr.com/ru/post/1678403/


All Articles