Below code works absolutely fine using JavaScript. I can print cell[5] in other words any specified index value. But I want to print this in a loop but it does not work. Does any one know why it does not work.
$(document).ready(function () {
var grid_arr = new Array();
var count = 0;
var cell;
cell = {
x1: 10,
y1: 10
};
alert(cell.x1);
for (i = 1; i < 10; i++) {
cell[i] = {
x1: i * 5,
y1: i * 2
};
}
alert(cell[5].x1);
});
/* The below for loop does not display any messages: */
for (var j = 0; j < 9; j++) {
alert(cell[j].x1);
}
4 Answers 4
Running that code throws a TypeError: Cannot read property 'x1' of undefined
This means the cell[j] part of cell[j].x1 is undefined.
Basically, when running:
for (var j = 0; j < 9; j++) {
alert(cell[j].x1);
}
cell[0] doesn't exist. The reason is that your for loops start counting at different numbers.
Either change that second for loop to start counting at 1, or change the first one:
for (i = 1; i < 10; i++) {
cell[i] = {
To start counting at 0.
Try to stay consistent in the way you initialize loops. Preferably, always initialize the index as 0, as most counting is zero-based in JS.
2 Comments
cell is a variable locally scooped to the anonymous function that you pass to ready.
This means you have two problems:
- The variable is not accessible globally
- The variable has not been assigned a value until after the ready event fires
Move your final loop inside the anonymous function or move all the code in that function outside it.
Your first loop also starts at 1 while your second starts at 0. This means that (once all the above are sorted) you will be attempting to alert undefined.x1 which will throw an exception.
Either start your loops at the same point, or test to make sure a value is defined before trying to read its properties.
Comments
Below code is working fine. Please try this.
var grid_arr = new Array(),
count = 0,
cell = new Array();
for (i = 1; i < 10; i++) {
cell.push({
x1: i * 5,
y1: i * 2
});
}
for (var j = 0; j < cell.length; j++) {
console.log(cell[j].x1);
}
Thanks,
1 Comment
cell's intended contents", you're right. (cell only has 9 properties) The problem in the OP's code is inconsistency in the for loops. That problem still exists in your answer.So many errors in so little code. grid_arr, count is unused. You don't need to use jQuery's document ready function for things that doesn't interact with the DOM. In the first for-loop your index starts from 1, then in your second for loop your index starts from zero. This is how you do it;
for( var cell = [], i = 1; i < 10; i++){
cell.push({
x1: i * 5,
y1: i * 2
});
alert( cell[i-1].x1 );
}
[]tonew Array()$(document).ready?for (i = 1; i < 10; i++) {why start from 1 ?