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?

4
  • 1
    Why do you want to do that in the first place? Commented Dec 3, 2013 at 13:59
  • 2
    Because matrix[3] doesn't exist. Commented Dec 3, 2013 at 14:00
  • you have to initialize array from zeroth index. you can not access directly third index before initialize. Commented Dec 3, 2013 at 14:01
  • var matrix = []; matrix[3] = [10]; print(matrix[3][0]); JS doesn't have multidimensional arrays in the sense that, say, Pascal does - JS has arrays of arrays. Commented Dec 3, 2013 at 14:12

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Well I have one more question. In case when I need to use more than one matrix array element then I have to initialize all of them in the loop or somwhere in the code initialize each matrix array element as array?
@user2968398 I'm not sure I understand you completely, but yes - before you use an element of any array as an array, it must be initialized. You don't have to do it ahead of time - you can check before trying to use it, and initialize it at that time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.