Access to ES6 array element index inside for-of loop
⚡TLDR
Surely implement array.entries()
with for-of
for a clear indexed loop:
Pairs index with value, making iteration simple and readable.
When you need the index
Indexing with array.keys()
If you're more interested in the indices than the values, array.keys()
focuses only on them:
Indexing in a pure for-of loop
You can also keep track of the index the old-fashioned way, with some manual labor:
Ultimate control with traditional for
When you need sophisticated control over your loop, for
loop is the swiss-army knife of looping:
Behind the scenes with .next()
Underneath the hood of for-of
loops lies the iterator protocol:
Beware of forEach and for-in
forEach
and for-in
may not behave as expected for array iteration:
Could a simple for loop be the way to go? Take your pick.
Linked
Linked
Was this article helpful?