Access to ES6 array element index inside for-of loop
We can access array elements using a for-of loop:
for (const j of [1, 2, 3, 4, 5]) {
console.log(j);
}
How can I modify this code to access the current index too? I want to achieve this using for-of syntax, neither forEach nor for-in.
Solution 1:
Use Array.prototype.keys
:
for (const index of [1, 2, 3, 4, 5].keys()) {
console.log(index);
}
If you want to access both the key and the value, you can use Array.prototype.entries()
with destructuring:
for (const [index, value] of [1, 2, 3, 4, 5].entries()) {
console.log(index, value);
}
Solution 2:
Array#entries
returns the index and the value, if you need both:
for (let [index, value] of array.entries()) {
}