1
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

Wintersun
  • 19
  • 2
  • 4
    that isn't a 2d array - its an array of arrawys. – Daniel A. White Nov 17 '16 at 13:53
  • Possible duplicate of [How can I create a two dimensional array in JavaScript?](http://stackoverflow.com/questions/966225/how-can-i-create-a-two-dimensional-array-in-javascript) – Liam Nov 17 '16 at 13:53
  • See also http://stackoverflow.com/questions/39325636/porting-c-sharp-3d-array-to-js-3d-array/39328793#39328793 , there is a proposed mini-library for a kind-of a multi-dimensional JS array. It is for 3 dimensions but you surely can modify it for 2. – Andrew Sklyarevsky Nov 17 '16 at 13:55

3 Answers3

6

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);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Hi, thank you for your explanation. But how do I create a 2D Array then? The index is supposed to be a number I get from a Database. So it won't be 0 - N, rather somethin glike : 5 , 10, 100, 200, 300, 300, 400 ,500. – Wintersun Nov 21 '16 at 07:44
  • @Wintersun — You can't. I refer you back to the very first sentence of the answer. You have to explicitly create an array at the index of the outer array where you want it. – Quentin Nov 21 '16 at 09:20
0

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)
Liam
  • 27,717
  • 28
  • 128
  • 190
Eliran
  • 157
  • 1
  • 13
0

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);
Anand Singh
  • 2,343
  • 1
  • 22
  • 34