Search code examples
javascriptfor-loopindexed

What is the simple way to get value and index on For of loop out of an array in Javascript / ReactNative?


I understand that for of is to get the element from an array in Javascript.

for (let element of array) {
  // do something with element
}

The problem is that I can't get the index inside the loop.

But I remember that at some time in the past, I have read that I can also get the index within the loop using syntax that more or less like this:

for ((index, element) of array.indexed()) {
  // can access both index and element here
}

But it's hard to find it amidst of the many faces of for loop syntax alternative of Javascript. One of the answer I read is here that contains tons of indexed for loop alternative, but nothing like what I've described above.


Solution

  • use this

    for (const [index, value] of array.entries()) {
      console.log(index, value);
    }