Home > other >  Why am I getting an error with this multidimensional array?
Why am I getting an error with this multidimensional array?

Time:02-07

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]);

Yet, this code does not work.

var occupied = [[],[]];
occupied[2][0] = 0;
console.log(occupied[2][0]);

It also works with occupied[0][0]. Just not anything above 1.

CodePudding user response:

That's because you have defined only two items in your array (index 0 and index 1). So there is no index 2.

//      index:   0   1
var occupied = [ [], [] ];
occupied[1][0] = 0;
// works, index 1 exists
console.log(occupied[1][0]);
// error, index 2 doesn't exist
console.log(occupied[2][0]);

CodePudding user response:

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.

Now , as line 2 is, occupied[2][0] = 0 ; here occupied[2][0] is undefined and you cannot store anything inside undefined , which is causing you an error :)

CodePudding user response:

occupied[1][0] = 0; works because the length of occupied is 2. occupied[1] will access the second node, which is an empty array occupied[1][0] = 0; this will assign 0 to the first element of the second node of occupied array.

var occupied = [
  [], // Index 0
  [], // Index 1 => occupied[1][0] will access the first item of empty array in this location
];
occupied[1][0] = 0;
console.log(occupied[1][0]);
console.log(occupied);

occupied[2][0] = 0; this will not work. works because the length of occupied is 2. occupied[2] will try to access the third node occupied array, which donot exist. In this case occupied[2] is undefined. occupied[2][0] = 0; will try to set 0 to zeroth index of an undefined variable, this will throw a refrence errror like

Uncaught TypeError: Cannot set properties of undefined (setting '0')
  •  Tags:  
  • Related