Austin Truex Austin Truex - 1 year ago 75
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++) {
console.log(itemIds); // outputs as expected, the same thing, data.length times

But this does not work (the only change is adding
into the

itemIds = [];
for (var i = 0; i <= data.length; i++) {
console.log(itemIds); // TypeError: Cannot read property 'item' of undefined

I need to do this as
in this example is coming from an angular
call, and returning an object. I don't understand why statically putting in 0 works, but trying to make it iterate through each
does not.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download