I am really having a hard time trying to fill my two dimensional array in Javascript.
I have a different array with lots of letters that I want to add to my ‘board’ but even the board dose not seem to be working correctly. Whenever I try to print board to the web page using the draw Board method I get NaN for the place where the letter A is. The rest is displaying the number 0.
var ROW = 10;
var COLUMN = 10;
var board = [['A', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]];
function drawBoard(board) {
var str = '';
for (var x = 0; x < ROW; x++){
str += '<div class="row">';
for (var y = 0; y < COLUMN; y++){
str += '<div class="column">' +
+ board[x][y] + '</div>' + '</div>';
}
str += '</div>';
}
$('#board').append(str);
}
$(function(){
drawBoard(board);
});
What I want to do is have this string:
var Letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'];
make a for loop to just board[x][y] = Letters.pop(). And then display the board with the new letters.
Are there any better ways to add an array to a two dimentional array than just running two for loops?
Why dose my board display NaN and not the letter. I have tried many different things.
To answer the first question. If you look at your code:
you can see that you have a
+ +board[x][y], not a+when addingboard[x][y]. The unary+tries to convert the value ofboard[x][y]to a number before concatenating giving you theNaNerror( as @Bergi pointed out).To add an element to the end of an array you can use the
push()method (in your caseboard.push(Letters)). This will place the element, which can be an array, at the end of the array.If you want to replace a line in the array you can use
board[x] = Letters.