Could someone give me an explanation as to why this works
itemIds = [];
for (var i = 0; i <= data.length; i++) {
itemIds.push(data[0].item);
}
console.log(itemIds); // outputs as expected, the same thing, data.length times
But this does not work (the only change is adding i
into the push()
)
itemIds = [];
for (var i = 0; i <= data.length; i++) {
itemIds.push(data[i].item);
}
console.log(itemIds); // TypeError: Cannot read property 'item' of undefined
I need to do this as data
in this example is coming from an angular $http
call, and returning an object. I don't understand why statically putting in 0 works, but trying to make it iterate through each data.item
does not.
Could someone give me an explanation as to why this works
itemIds = [];
for (var i = 0; i <= data.length; i++) {
itemIds.push(data[0].item);
}
console.log(itemIds); // outputs as expected, the same thing, data.length times
But this does not work (the only change is adding i
into the push()
)
itemIds = [];
for (var i = 0; i <= data.length; i++) {
itemIds.push(data[i].item);
}
console.log(itemIds); // TypeError: Cannot read property 'item' of undefined
I need to do this as data
in this example is coming from an angular $http
call, and returning an object. I don't understand why statically putting in 0 works, but trying to make it iterate through each data.item
does not.
5 Answers
Reset to default 4This is because your variable i
will eventually increment above the length of the array.
You need to change your for loop from i <= data.length
to i < data.length
.
This will ensure that the i
variable will always be within the bounds of the array.
Considering that the index is zero-based, but the length will count up from one, the length will always be one more than the highest index.
Here is my dummy explanation.
i
can never be equal to data.lenght
If for example:
var data = ['Bob', 'John', 'Mike'];
data[0] = Bob
data[1] = John
data[2] = Mike
data[3] = ?
Therefore data[3]
cannot be equal to data.length = 3
, it starts looping through 0.
Hope it helps for newbies.
Just to demostrate what goes wrong
basket = ['milk', 'egg', 'chees']
for (var i = 0; i <= basket.length; i++) {
console.log('loop ' + i, basket[i])
}
/*
Logs:
loop 0 milk
loop 1 egg
loop 2 chees
loop 3 undefined
*/
Change
for (var i = 0; i <= data.length; i++)
to
for (var i = 0; i < data.length; i++)
basket = ['milk', 'egg', 'chees']
var x = "";
for (var i = 0; i <= basket.length; i++) {
x = 'loop ' + i, basket[i];
console.log(x);
}
Hope it solves the problem. 'loop ' + i, basket[i]; -- itself creates an empty unidentified element if is not declared with a variable and variable must have an empty content, like this var x = "";
itemIds.push(data[i][item])
; – Phillip Chan Commented Nov 1, 2016 at 21:11<=
to just<
and you are all good – Endless Commented Nov 1, 2016 at 21:12undefined
elements into an array. – Phillip Chan Commented Nov 1, 2016 at 21:13