Weird Behaviour when nesting 2D arrays in a 3D array

Viewed 29

Currently I'm working on a Minimax algorithm for four-in-a-row in javascript. I have decided to store possible moves in a array, continuing to nest arrays within arrays for every branch.

However, when I attempt to edit a certain value in an array, it edits all other values within the same column.

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 dimension index number. This issue only happens when I use an existing array nested within an array. If I were to make a 3D array from scratch, this bug does not happen.

2 Answers
Related