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.
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'); } }
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
Although you have declared array as 3D array, JavaScript do not allocate the memory to it.
So being 3D array sec[0] is undefined.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.