Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 384
Abdennour TOUMI Avatar asked Dec 18 '15 05:12

Abdennour TOUMI


People also ask

Can you access an element in an array by using its index?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.

How can you access the elements of an indexed array?

Access Array Elements Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.


1 Answers

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);  }
like image 105
Michał Perłakowski Avatar answered Sep 22 '22 15:09

Michał Perłakowski