Generator 函数

来源:互联网 发布:java获取客户端端口号 编辑:程序博客网 时间:2024/06/07 20:53

Generator 函数是一个普通函数,但是有两个特征。一是,function关键字与函数名之间有一个星号;二是,函数体内部使用yield表达式,定义不同的内部状态(yield在英语里的意思就是“产出”)。

执行 Generator 函数会返回一个遍历器对象,也就是说,Generator 函数除了状态机,还是一个遍历器对象生成函数。返回的遍历器对象,可以依次遍历 Generator 函数内部的每一个状态。

function* helloWorldGenerator() {  yield 'hello';  yield 'world';  return 'ending';}var hw = helloWorldGenerator();

然后,Generator 函数的调用方法与普通函数一样,也是在函数名后面加上一对圆括号。不同的是,调用 Generator 函数后,该函数并不执行,返回的也不是函数运行结果,而是一个指向内部状态的指针对象,也就是上一章介绍的遍历器对象(Iterator Object)。

下一步,必须调用遍历器对象的next方法,使得指针移向下一个状态。也就是说,每次调用next方法,内部指针就从函数头部或上一次停下来的地方开始执行,直到遇到下一个yield表达式(或return语句)为止。换言之,Generator 函数是分段执行的,yield表达式是暂停执行的标记,而next方法可以恢复执行。

hw.next()// { value: 'hello', done: false }hw.next()// { value: 'world', done: false }hw.next()// { value: 'ending', done: true }hw.next()// { value: undefined, done: true }
yield表达式如果用在另一个表达式之中,必须放在圆括号里面。
function* demo() {  console.log('Hello' + yield); // SyntaxError  console.log('Hello' + yield 123); // SyntaxError  console.log('Hello' + (yield)); // OK  console.log('Hello' + (yield 123)); // OK}next 方法的参数
 yield表达式本身没有返回值,或者说总是返回undefinednext方法可以带一个参数,该参数就会被当作上一个yield表达式的返回值。

next 方法的参数


function* f() {  for(var i = 0; true; i++) {    var reset = yield i;    if(reset) { i = -1; }  }}var g = f();g.next() // { value: 0, done: false }g.next() // { value: 1, done: false }g.next(true) // { value: 0, done: false }
上面代码先定义了一个可以无限运行的 Generator 函数f,如果next方法没有参数,每次运行到yield表达式,变量reset的值总是undefined。当next方法带一个参数true时,变量reset就被重置为这个参数(即true),因此i会等于-1,下一轮循环就会从-1开始递增。

for...of 循环 

function *foo() {  yield 1;  yield 2;  yield 3;  yield 4;  yield 5;  return 6;}for (let v of foo()) {  console.log(v);}// 1 2 3 4 5
上面代码使用for...of循环,依次显示5个yield表达式的值。这里需要注意,一旦next方法的返回对象的done属性为truefor...of循环就会中止,且不包含该返回对象,所以上面代码的return语句返回的6,不包括在for...of循环之中。

下面是一个利用 Generator 函数和for...of循环,实现斐波那契数列的例子。

function* fibonacci() {  let [prev, curr] = [0, 1];  for (;;) {    [prev, curr] = [curr, prev + curr];    yield curr;  }}for (let n of fibonacci()) {  if (n > 1000) break;  console.log(n);}
yield*表达式,用来在一个 Generator 函数里面执行另一个 Generator 函数。

function* bar() {  yield 'x';  yield* foo();  yield 'y';}// 等同于function* bar() {  yield 'x';  yield 'a';  yield 'b';  yield 'y';}




原创粉丝点击