user1337
user1337

Reputation: 175

Multidimensional array javascript with index starting not from 0

I need to fill multidimensional array but not from zeroth element but from i.e. 3rd, but got errors when trying to do that:

code is:

var matrix = [ [] ];
matrix[3][0] = 10;
print(matrix[3][0]);

then got error: "Unable to set value of the property '0': object is null or undefined"

but when do same from zeroth element then it works:

var matrix = [ [] ];
matrix[0][0] = 10;
print(matrix[0][0]);

No errors here - why?

Upvotes: 0

Views: 121

Answers (1)

Pointy
Pointy

Reputation: 413818

When you create your initial array:

var matrix = [ [] ];

you've got an array with a single zero-element array in it. At that point, matrix[3] is undefined.

You can initialize your matrix in several ways, depending on the nature of your problem. Here's one:

var matrix = [];
for (var i = 0; i < 10; ++i)
  matrix[i] = [];

Now you've got 10 rows, each one empty.

Upvotes: 3

Related Questions