Skip to content Skip to sidebar Skip to footer

Why Am I Getting An Error With This 2d Array?

var arr = [[],[]]; var si = 5; var c = 0; if (arr[si][c] == null) { arr[si][c] = { code : 'Test', }; } alert(arr[si][c].code); Hello, I am trying to run this

Solution 1:

JavaScript doesn't have any concept of 2 dimensional arrays. Just arrays that contain other arrays.

arr[si][c] is arr[5][0].

arr is an array with two members (0 and 1), each of which is an array.

When you access arr[5] you get undefined because you have gone beyond the end.

undefined[0] is an error.

The awkward thing is that if I use numeric values instead of the variables "si" and "c" for the index, the error doesn't show up!

You get the same error if you use literals instead of variables. Presumably your working test involved different numbers.

var arr = [[],[]];
if (arr[5][0] == null)
{
     arr[5][0] = {
           code : "Test",
     };
}
alert(arr[5][0].code);

Solution 2:

you may try first check if arr[si].length-1 is bigger or equal to c. something like this:

if((arr[si].length-1)>c)

Solution 3:

You are accessing not defined array index arr[5] i.e 5 ,as in definition arr has two element [] and [], so that it would have index 0 and 1 so if you set si as 1 or 0 it will work.

var arr = [[],[]];
var si = 1;
var c  = 0;
if (arr[si][c] == null)
{
     arr[si][c] = {
           code : "Test",
     };
}
alert(arr[si][c].code);

Post a Comment for "Why Am I Getting An Error With This 2d Array?"