Austin Truex Austin Truex - 1 month ago 6
Javascript Question

pushing data into array inside a for loop JavaScript

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.

Answer

This 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.

Comments