0

Since for of is the standardized es6, but how to use the index?

let list = [4, 5, 6];

for (let i in list) {
   console.log(i); // "0", "1", "2",
}

for (let i of list) {
   console.log(i); // "4", "5", "6"
}
Mellisa
  • 605
  • 3
  • 12
  • 22
  • 1
    If you are in need of the index, you shouldn't be using `for ... of`. – Jelle den Burger Mar 02 '17 at 11:54
  • @Jelle [You can absolutely](http://stackoverflow.com/questions/33538944/how-can-the-current-number-of-i-be-accessed-in-a-for-of-loop) use `for..of` to retrieve the index if required. – CodingIntrigue Mar 02 '17 at 14:59
  • @CodingIntrigue ofcourse it is possible, but `for ... of` is not meant for it. – Jelle den Burger Mar 02 '17 at 15:01
  • @Jelle `for..of` is meant for iterators. An iterator can return a series of indices. I'm not sure I see anything wrong with that. – CodingIntrigue Mar 02 '17 at 15:39
  • @CodingIntrigue The whole point of `for ... of` is to achieve object iteration, aka not working with indices. In comparision: you're not gonna write a `for (var entity in list) {}` in C#, when you're in need of an index, right? – Jelle den Burger Mar 02 '17 at 15:45
  • @Jelle This probably isn't the right medium for this, but I don't agree. Objects don't need to expose a `length`, but they may expose an index via the iterator itself. Seems fine. – CodingIntrigue Mar 02 '17 at 15:48

0 Answers0