1. Overview
Generator is a new data type introduced by ES6 and looks like a function that yields can be returned multiple times, in addition to returning with return.
Generator is defined by the function*, (note the * number),
2. Example
Functions cannot save state, sometimes global variables are required to hold numbers;
2.1
' Use strict ';functionnext_id () {varID = 1; while(id<100) {yield id; ID++; } returnID;}//Test:varx, pass=true, G=next_id (); for(x = 1; x < x + +)) { if(G.next (). Value!==x) {Pass=false; Alert (' Test failed! '); Break; }
}if(pass) {alert (' Test pass! ');}
2.2 An iterative iterator with infinite loops
function* idmaker () { var index = 0; while (true) yield index+ +;} var // "Generator {}" / /0// 1// 2
2.3generator.prototype.next ()
When the iteration ends, Generator.next (). Done ===true, before end ===false
function* gen () { 1; 2; 3;} var // "Generator {}"g.next (); // "Object {value:1, done:false}"G.next (); // "Object {value:2, done:false}"G.next (); // "Object {value:3, done:false}"G.next (); // "Object {value:undefined, done:true}"
2.4 Generator.prototype.return ();
The return method returns the given parameter value and ends the iterator
Example
function* gen () { 1; 2; 3;} var g = Gen (); G.next (); // {value:1, done:false}G.return// {value: "foo", Done:true}g.next ();
// {value:undefined, done:true}
Note If the done value is true, then call return, and the returned value is also undefined
function* Gen () {yield 1;} var g = Gen (); Console.log (G.next ()); // {value:1, done:false}Console.log (G.next ()); // {value:undefined, done:true}Console.log (g.return//{value:undefined, done:true}
2.5 Generator.prototype.throw ()
The Thorw () method, by throwing an exception into the iterator, to regain the execution of the iterator;
Returns an object with value and done two properties
function*Gen () { while(true) { Try{yield42; } Catch(e) {Console.log ("Error caught!"); } }}varg =Gen ();varA =G.next ();//{value:42, done:false}varb = g.Throw(NewError ("Something went wrong"));//"Error caught!"//{value:42, done:false}Console.log (a); Console.log (B.value+ "::" +b.done);
JS Generator Data type