How to loop the JavaScript iterator that comes from generator?
The best way to iterate any iterable (an object which supports @@iterator), is to use for..of
, like this
'use strict';
function * gen() {
for (var i = 0; i < 10; i++) {
yield i;
}
}
for (let value of gen()) {
console.log(value);
}
Or, if you want an Array out of it, then you can use Array.from
, like this
console.log(Array.from(gen());
// [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]