var UserBoard = new Array(20,20);
for(var i = 0; i < 21; ++i){
for(var j = 0; j < 21; ++j){
UserBoard[i,j] = 0;
}
}
document.write(UserBoard[3,5]);
UserBoard[4,5]=1;
document.write(UserBoard[3,5]);
it’s quite simple but I don’t know why does this. Alert should be 0, not 1 since I’ve initialized the 2d array to 0.
Can someone explain me why?
Let’s break it down
You are creating an array with two slots, both of them containing the value “20” (int). So your array is
[20, 20]Next, your loop :
Two dimensional arrays are not defined like this. In that case, only the “j” counter does something. The “i” is simply ignored. So you end up with an array as follow :
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]Next, the assignement :
Is equivalent to :
And your alert :
Is equivalent to :
That’s why you get “1” as alert.
If you want two dimensional arrays, you should use the following notation :
Read it all here on MDN : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array