1

this is my code :

var y = new Array(); // it have 500 entries.
var z = [[]];
    var counter =0;
    for(var i =0; i<49;i++){
        for(var j=0; j<9;j++){
            z[i][j] = y[counter];
            counter +=1;
        }
    }
    console.log(z);

and I am getting this error : TypeError: 'undefined' is not an object (evaluating 'z[i][j] = y[counter]')

what am I doing wrong ?

1
  • You are trying to access z[0][1] which doesn't exist. var z = [[]]; creates an array with a single element (another array). JavaScript doesn't have multidimensional arrays, you have to create every element of an array explicitly. Commented Mar 17, 2015 at 15:08

1 Answer 1

4

You have to initialize each row of the two-dimensional array. Your declaration:

var z = [[]];

only creates row 0.

So:

for(var i =0; i<49;i++){
    z[i] = []; // <===== initialize the row
    for(var j=0; j<9;j++){
        z[i][j] = y[counter];
        counter +=1;
    }
}
Sign up to request clarification or add additional context in comments.

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.