Wintersun
Wintersun

Reputation: 19

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 sample code but I am getting an error, saying that the attribute "0" of an undefined can not be called.

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!

Is it possible that in JS you can not use variables as an Index? I think it does work with a non two dimensional array.

Thank you and best regards

Upvotes: 1

Views: 513

Answers (3)

Anand Singh
Anand Singh

Reputation: 2363

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

Upvotes: 0

Eliran
Eliran

Reputation: 157

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)

Upvotes: 0

Quentin
Quentin

Reputation: 943142

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

Upvotes: 6

Related Questions