0

I have an object, cards, which is made up of other objects.

When I loop through cards, I expect other objects to get returned. Instead, only a string is returned. I've included what gets returned inline in the code below.

console.log(typeof cards); //returns object
console.log(cards); //returns the 3 objects: [Object, Object, Object]
console.log(cards.length); //returns 3

for (var card in cards){
    console.log(typeof card); //returns 0,1,2 as a string, but it should return another object
};
sharataka
  • 5,014
  • 20
  • 65
  • 125

1 Answers1

1

for...in loops iterate properties of an object, not values.

For example:

var cards = ['a', 'b', 'c'];
for(var prop in cards) {
    console.log(prop);        //  0,   1,   2
    console.log(cards[prop]); // 'a', 'b', 'c'
}

Moreover, note that for...in loops are a bad way of iterating arrays.

ECMAScript 6 introduces for...of loops, which iterate values:

var cards = ['a', 'b', 'c'];
for(var val of cards) {
    console.log(val);         //  'a', 'b', 'c'
}
Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513