Reputation: 86
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);
}
Upvotes: 0
Views: 172
Reputation: 69
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 );
}
Upvotes: 0
Reputation: 831
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,
Upvotes: 0
Reputation: 72839
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.
Upvotes: 1
Reputation: 943142
cell
is a variable locally scooped to the anonymous function that you pass to ready
.
This means you have two problems:
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.
Upvotes: 0