Caution:
question still applies to
for…of
loops.> Don't usefor…in
to iterate over an Array, use it to iterate over the properties of an object. That said, this
I understand that the basic for…in
syntax in JavaScript looks like this:
for (var obj in myArray) {
// ...
}
But how do I get the loop counter/index?
I know I could probably do something like:
var i = 0;
for (var obj in myArray) {
alert(i)
i++
}
Or even the good old:
for (var i = 0; i < myArray.length; i++) {
var obj = myArray[i]
alert(i)
}
But I would rather use the simpler for-in
loop. I think they look better and make more sense.
Is there a simpler or more elegant way?
In Python it's easy:
for i, obj in enumerate(myArray):
print i
As others have said, you shouldn't be using for..in to iterate over an array.
If you want cleaner syntax, you could use forEach:
If you want to use this method, make sure that you include the ES5 shim to add support for older browsers.
For-in-loops iterate over properties of an Object. Don't use them for Arrays, even if they sometimes work.
Object properties then have no index, they are all equal and not required to be run through in a determined order. If you want to count properties, you will have to set up the extra counter (as you did in your first example).
loop over an Array:
loop over an Object: