2

I am trying to convert Java code to Javascript and I am trying to assign data to 3 dimensional array and I am getting "TypeError: can't convert undefined to object " error. Following is my code. Thanks in advance for any help.

var initData = [[2], [12], [2]];

for (var i = 0; i < 12; i++)
{
    initData[0][i][0] = -1;
    initData[0][i][1] = -1;
    initData[1][i][0] = -1;
    initData[1][i][1] = -1;
}
4
  • 3
    Well, you have a 2D array. Commented Aug 6, 2013 at 16:05
  • 1
    Your initData is a 2 dimentional array of arrays, each of those arrays has a single cell. I don't think this is what you meant. Commented Aug 6, 2013 at 16:05
  • 2
    You cannot declare dimensions of javascript arrays, because there are no multidimensional arrays in JS. They're just one-dimensional lists that can contain arbitrary values (including other lists). Commented Aug 6, 2013 at 16:06
  • in your code, [12] is an array containing one element (the number 12). Commented Aug 6, 2013 at 16:08

2 Answers 2

1
[[2], [12], [2]];

That's not a declaration of dimensions, that's four array literals. There are no multidimensional arrays in JS. They're just one-dimensional lists that can contain arbitrary values (including other lists).

To create and fill an array that contains other arrays you have to use the following:

var initData = []; // an empty array
for (var i = 0; i < 2; i++) {
    initData[i] = []; // that is filled with arrays
    for (var j = 0; j < 12; j++) {
        initData[i][j] = []; // which are filled with arrays
        for (var k = 0; k < 2; k++) {
            initData[i][j][k] = -1; // which are filled with numbers
        }
    }
}

or, to apply your loop unrolling:

var initData = [[], []]; // an array consisting of two arrays
for (var i = 0; i < 12; i++) {
    // which each are filled with arrays that consist of two numbers
    initData[0][i] = [-1, -1];
    initData[1][i] = [-1, -1];
}
Sign up to request clarification or add additional context in comments.

Comments

0

initData is a list of three lists, [2], [12] and [2]. Each one with one element.

In order to init a list(or array), you must do

var initData = [];

Then store in initData another list, like initData[0] = [] and so on... like it's mentioned, arrays/lists in javascript aren't initialized with a limit size.

Comments

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.