Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 206
Truextacy Avatar asked Nov 01 '16 21:11

Truextacy


1 Answers

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.

like image 151
Daniel Hall Avatar answered Sep 27 '22 18:09

Daniel Hall