-8

For me this looks odd:

products = ["Item1", "Item2", "Item3"];
for (var x in products) {
  debugger;
  console.log(x);
  // x === "0" instead of "Item1"
}

I wonder why?

Incerteza
  • 32,326
  • 47
  • 154
  • 261
  • What's happening here is that the `x` variable is actually the current index that you are iterating over. `0` is the first index. To get the actual value you would have to do `products[x]` – Lix Apr 12 '15 at 11:34
  • This is also a duplicate of [Why for var in array returns a string index?](http://stackoverflow.com/questions/26819769/why-for-var-in-array-returns-a-string-index) (it appears my comment earlier was deleted for some weird reason) – Qantas 94 Heavy Apr 12 '15 at 12:34
  • @Qantas94Heavy, yes it is. And of many others as well. – Incerteza Apr 12 '15 at 12:38

3 Answers3

4

for..in loops over enumerable properties and arrays have numerical properties which acts as index. It is to be used with only objects.

Doing so with Arrays will also give you properties which you won't be interested in(such as those properties which are on the higher chain of prototypic inheritance from Object object)

So use a simple for loop or Array.forEach

products.forEach(function(str){
   console.log(str);
});
// or
for(var i = 0; i < products.length; i++)
   console.log(products[i]);
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • 4
    In a comment on your moderator election nomination, you said that answering questions which were obvious duplicates was a one-off case in the past. Do you believe answering this question goes against your moderation philosophy? – Qantas 94 Heavy Apr 12 '15 at 11:37
  • @Qantas94Heavy moderation isn't close-voting. Close-voting is to be done by all the members of the SO community. What a mod actually does is handle flags and some exceptional cases. Regarding answering this, I'd have used my golden hammer. But the current SO search sucks and when I came across this question, it was *already* answered which according to me was not correct. So answered it. – Amit Joki Apr 12 '15 at 11:46
1

That's because in your case, variable x is holding the array item's index, and not the value. Instead of x, you should use products[x].

products = ["Item1", "Item2", "Item3"];
for (var x in products) {
  debugger;
  console.log(products[x]);
}

Now, instead of:

0
1
2

you'll get

Item1
Item2
Item3
Amar Syla
  • 3,523
  • 3
  • 29
  • 69
-1

Iterate over the array like this. U use var in arr if you want to iterate over properties of an object, not an array!

var products = ["Item1", "Item2", "Item3"];
for (var i =0; i< products.length;i++) {
  debugger;
  console.log(products[i]);
  // x === "0" instead of "Item1"
}
Legends
  • 21,202
  • 16
  • 97
  • 123