Reputation: 233
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.
Upvotes: 0
Views: 199
Reputation: 234867
Like minitech said in a comment: you need a distinct array for each column of board
. Try this:
function createTableArray() {
var boardSize = 5;
var board = new Array(boardSize);
for (var i=0; i<boardSize; i++) {
var boardCol = new Array(boardSize);
for (var j=0; j<boardSize; j++) {
boardCol[j] = getRandomColVal(i, boardSize - j);
}
board[i] = boardCol;
}
return board;
}
Upvotes: 2