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
In ES6, it is good to use for - of loop. You can get index in for of like this
Note that
Array.entries()
returns an iterator, which is what allows it to work in the for-of loop; don't confuse this with Object.entries(), which returns an array of key-value pairs.for…in
iterates over property names, not values, and does so in an unspecified order (yes, even after ES6). You shouldn’t use it to iterate over arrays. For them, there’s ES5’sforEach
method that passes both the value and the index to the function you give it:Or ES6’s
Array.prototype.entries
, which now has support across current browser versions:For iterables in general (where you would use a
for…of
loop rather than afor…in
), there’s nothing built-in, however:demo
If you actually did mean
for…in
– enumerating properties – you would need an additional counter.Object.keys(obj).forEach
could work, but it only includes own properties;for…in
includes enumerable properties anywhere on the prototype chain.Solution for small array collections:
arr - ARRAY, obj - KEY of current element, i - COUNTER/INDEX
Notice: Method keys() is not available for IE version <9, you should use Polyfill code. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
How about this
Where
array.forEach
this method has anindex
parameter which is the index of the current element being processed in the array.Here's a function
eachWithIndex
that works with anything iterable.You could also write a similar function
eachWithKey
that works with objets usingfor...in
.The good thing with generators is that they are lazy and can take another generator's result as an argument.
That's my version of a composite iterator that yields an index and any passed generator function's value with an example of (slow) prime search: