Javascript Generator Create with while loop

Introduction

When a generator reaches the yield keyword, it pauses and returns the current value.

The next time the next() method is called, the generator will continue to run, thereby creating a new value.

function *numCount(){ 
   let count = 0; 
   while(count < 5) 
      yield count++; /*  ww w  .  j av a2s.co  m*/
} 

let irt = numCount(); 
console.log(irt.next()); //Object {value: 0, done: false} 
console.log(irt.next()); //Object {value: 1, done: false} 
console.log(irt.next()); //Object {value: 2, done: false} 
console.log(irt.next()); //Object {value: 3, done: false} 
console.log(irt.next()); //Object {value: 4, done: false} 
console.log(irt.next()); //Object {value: undefined, done: true} 



PreviousNext

Related