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?
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?
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]);
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
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"
}