0

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.

Chen Li Yong
  • 5,459
  • 8
  • 58
  • 124
  • 2
    Does this answer your question? [Access to ES6 array element index inside for-of loop](https://stackoverflow.com/questions/34348937/access-to-es6-array-element-index-inside-for-of-loop) – Álvaro Tihanyi Jun 29 '20 at 11:03
  • 1
    why dont you use a classic `for` loop? – bill.gates Jun 29 '20 at 11:05
  • `for...of` is used when you just want to do something with the iteratable items and don't care about their index. If you want to get the index, why not use a normal [`for`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) loop? You could use `array.entries()`, but they are confusing when someone else looks at your code. Just because newer features are available, doesn't mean that `for` loop has become deprecated or unfashionable – adiga Jun 29 '20 at 11:08
  • @adiga I want to avoid the `{ let element = array[i]` code after the for. – Chen Li Yong Jun 30 '20 at 03:51

1 Answers1

1

use this

for (const [index, value] of array.entries()) {
  console.log(index, value);
}
Sven.hig
  • 4,449
  • 2
  • 8
  • 18
  • Thanks! Too many similar language confuses me. I know I can mark this, but if I want to search this later on on Google, how should I form my search query? With simple for of text for query, it's hard to find answer like this. What is the keyword to search this form of for? – Chen Li Yong Jun 30 '20 at 03:56