0

If i have an array:

[1, 2, 3, 4, 5] - 

I can loop with:

for (let [i, x] of arr.entries()){..}

If i have a generator function:

function* g() {
   yield 1; yield 2; yield 3;
}

I cannot.

So the questions is how to get index and key of loops with for of and generator.

Is there the same syntax for both regular array and generator.

And lastly why generators hasnt method "entries" since they are both iterable.

Whats the point of iterable if they are accessed in different ways.

  • 2
    See https://stackoverflow.com/questions/10179815/how-do-you-get-the-loop-counter-index-using-a-for-in-syntax-in-javascript/10179849#10179849, “for iterables in general”. `entries()` is for map-like things, which generators aren’t (you can’t do `g()[0]`). – Ry- Jun 25 '18 at 06:19
  • Generators don't create the entire array. they run another iteration of the function every time a `next` is called. generators are usually infinite. That's one of the reasons an `entries` function won't work good enough for your code. – Thatkookooguy Jun 25 '18 at 06:22

2 Answers2

2

Actually generators works a bit differently than normal iterable data data structure. just for fun if you want index and values out of some generator you can if what you are yielding does have a index. you cant yield anything you need.

function* gen() {
 const a = [3, 5, 6];
  for (let  [key, value] of a){
   yield [key, value];
  }
}

for (let [i, x] of gen()){
  console.log(i, x);
}
shahin mahmud
  • 945
  • 4
  • 11
1

You basically want to use the Array.prototype.entries on a generator, that doesn't work in that way.

However, you can easily transform your generator in an array, and then use the entries method:

function* g() {
  yield 1; yield 2; yield 3;
}

for (let [i, x] of [...g()].entries()){..}
ZER0
  • 24,846
  • 5
  • 51
  • 54
  • 1
    Once a generator is transformed to an array just for iteration (in most cases, this is not possible, as generators can be infinite), the point of generators is lost IMHO. – thefourtheye Jun 26 '18 at 06:58
  • exactly. whats the use of using generators then :P – shahin mahmud Jun 26 '18 at 07:15
  • This is a perfect valid scenario (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators that basically has the same); and *if* we want to use methods like `entries` that's the most viable option. Otherwise, I totally agreed that the original question is flawed, since generators have a different data structure and they should be used differently. – ZER0 Jun 26 '18 at 08:00
  • The point of using a generator, compare to a flat array, is multiple. You don't have to calculate everything upfront – instead of the array – but only when the generator is called: you *may* want to have a "snapshot" of the generators for the iteration instead of a "living list" (e.g. the difference between a static nodelist and live htmlcollection), etc. – ZER0 Jun 26 '18 at 08:03