Truextacy
Truextacy

Reputation: 562

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.

Upvotes: 8

Views: 32510

Answers (5)

Rahul Sarkar
Rahul Sarkar

Reputation: 11

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 = "";

Upvotes: 1

Alberto Cerqueira
Alberto Cerqueira

Reputation: 1419

Change

for (var i = 0; i <= data.length; i++)

to

for (var i = 0; i < data.length; i++)

Upvotes: 1

carkod
carkod

Reputation: 2230

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.

Upvotes: 4

Endless
Endless

Reputation: 37806

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
*/

Upvotes: 3

Daniel Hall
Daniel Hall

Reputation: 166

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.

Upvotes: 4

Related Questions