I understand that the basic for...of syntax in JavaScript looks like this:
for (let obj of myArray) {
// ...
}
But how do I get the loop counter/index when iterating with this syntax?
(With the same question applying to for...in notation for iterating over object property names)
I know I can use an explicit loop counter like:
for (let i = 0; i < myArray.length; i++) {
const obj = myArray[i];
console.log(i);
}
Or manually track the index outside of the loop:
let i = 0;
for (let obj of myArray) {
console.log(i);
i++;
}
But I would rather use the simpler for...of loop, I think they look better and make more sense.
As an example of a language that lets you do this, in Python it’s as easy as:
for i, obj in enumerate(my_array):
print(i)
for…initerates 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’sforEachmethod 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…ofloop rather than afor…in), there’s nothing built-in, however:If you actually did mean
for…in– enumerating properties – you would need an additional counter.Object.keys(obj).forEachcould work, but it only includes own properties;for…inincludes enumerable properties anywhere on the prototype chain.