0

Following is my Code:

        var i,j;
        var period = 5;
        var sec = new Array(new Array(new Array()));
        for(i=0;i<6;i++){
            for(j=1;j<period;j++){  
                sec[j][i][j] = j;
                console.log("SEC: "+j+i+j+" = "+sec[j][i][j]);
                console.log('/n');
            }
        }

When I execute the above code I get cannot read property '0' of undefined at sec[j][i][j] assignment. I don't understand the reason behind it.. It would be great if you guys can help me on this. Thanks in advance.

0

3 Answers 3

4

That is because sec[1][0][1] is undefined, you need to push an array every time

        var i,j, period = 6;
        var sec = [];
        for(i=0;i<6;i++){
            for(j=1;j<period;j++){
                sec[j] = [];
                sec[j][i] = [];
                sec[j][i][j] = j;
                console.log("SEC: "+j+i+j+" = "+sec[j][i][j]);
                console.log('/n');
            }
        }

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

Comments

1
var sec = new Array(new Array(new Array()));

Doesn't do what you think it does. Try to allocate the inner arrays when needed like this instead

var i, j;
var period = 5;
var sec = [];
for (i = 0; i < 6; i++) {
  for (j = 1; j < period; j++) {
    sec[j] = sec[j] || [];
    sec[j][i] = sec[j][i] || [];
    sec[j][i][j] = j;
    console.log("SEC: " + j + i + j + " = " + sec[j][i][j]);
    console.log('\n');
  }
}

Also, /n prints '/n' not a new line which is \n

Comments

0

Although you have declared array as 3D array, JavaScript do not allocate the memory to it.

So being 3D array sec[0] is undefined.

2 Comments

so if I am not using sec[0] at all how do I proceed?
Refer @peter solution

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.