Sorry I really cant find the error in my code.
So i had this code which populates a 2 dimensional array with certain random values which act like a board and has a current size of 5x5.
function createTableArray() {
var boardSize = 5;
var board = new Array(boardSize);
var boardCol = new Array(boardSize);
var prevVal = 0;
for (var i=0;i<boardSize;i++) {
for (var j=0;j<boardSize;j++) {
boardCol[j] = getRandomColVal(i, boardSize - j);
}
board[i] = boardCol;
console.log(i + " within loop temp Col : " + boardCol);
console.log(i + " within loop Board : " + board[i]);
}
console.log("Before returning");
for (var i=0;i<boardSize; i++) {
console.log(i + " Board: " + board[i]);
}
return board;
}
I created a "before returning" log to check the board again but as a result all the board content only has the same values as the last boardCol. (Sorry for the poor explanation, I'll just present it visually).
It was supposed to be like this (since this is the value of boardCol when I logged it):
Array [ 5,8,12,13,14 ]
Array [ 20,24,25,27,28 ]
Array [ 38,39,40,41,43 ]
Array [ 48,54,55,56,57 ]
Array [ 64, 67, 71, 72, 73 ]
But it turned out like this:
Array [ 68, 71, 72, 73, 74 ]
Array [ 68, 71, 72, 73, 74 ]
Array [ 68, 71, 72, 73, 74 ]
Array [ 68, 71, 72, 73, 74 ]
Array [ 68, 71, 72, 73, 74 ]
Sorry, I really don't get how it all have the same values.
boardColinside the loop that fillsboard, or they’ll all just be references to the same array.