How do you access the index of an element in an array during iteration?
TL;DR
To access the index of an element in an array during iteration, you can use methods like forEach
, map
, for...of
with entries
, or a traditional for
loop. For example, using forEach
:
Using forEach
The forEach
method executes a provided function once for each array element. The callback function takes three arguments: the current element, the index of the current element, and the array itself.
Using map
The map
method creates a new array populated with the results of calling a provided function on every element in the calling array. The callback function also takes three arguments: the current element, the index of the current element, and the array itself.
Using for...of
with entries
The for...of
loop can be combined with the entries
method to access both the index and the element.
Using a traditional for
loop
A traditional for
loop gives you direct access to the index.