I'm still new to Javascript and trying to understand multi-dimensional arrays. Why does the following code work?
var occupied = [[],[]];
occupied[1][0] = 0;
console.log(occupied[1][0]);
That's because you have defined only two items in your array (index 0 and index 1). So there is no index 2.
Size of your occupied array is 2 . So the maximum index you can access is 1. If you try to access any index above 1 it means that you are accessing undefined.
here occupied[2][0] is undefined and you cannot store anything inside undefined , which is causing you an error :)
occupied[1][0] = 0;<\/code> works because the length of
occupied<\/code> is 2.
occupied[1]<\/code> will access the second node, which is an empty array
occupied[1][0] = 0;<\/code>
this will assign 0 to the first element of the second node of
occupied<\/code> array.
works because the length of occupied<\/code> is 2.
occupied[2]<\/code> will try to access the third node
occupied<\/code> array, which donot exist.
In this case
occupied[2]<\/code> is undefined.
occupied[2][0] = 0;<\/code> will try to set 0 to zeroth index of an undefined variable, this will throw a refrence errror like
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.