生成器函数中的委托产量(产量星,产量*) [英] Delegated yield (yield star, yield *) in generator functions

查看:19
本文介绍了生成器函数中的委托产量(产量星,产量*)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ECMAScript 6 应该带来生成器函数和迭代器.生成器函数(具有 function* 语法)返回一个迭代器.迭代器有一个 next 方法,当重复调用时,它执行生成器函数的主体,在每个 yield 操作符处重复暂停和恢复执行.

ECMAScript 6 should be bringing generator functions and iterators. A generator function (which has the function* syntax) returns an iterator. The iterator has a next method which, when repeatedly called, executes the body of the generator function, repeatedly pausing and resuming execution at every yield operator.

ECMAScript 6 wiki on generators 还引入了委托收益"yield* 运算符如下:

The ECMAScript 6 wiki on generators also introduces the "delegated yield" yield* operator as follows:

yield* 运算符委托给另一个生成器.这为组合生成器提供了便利的机制.

The yield* operator delegates to another generator. This provides a convenient mechanism for composing generators.

委托给另一个生成器"是什么意思?如何使用 yield* 来方便地组合生成器"?

What does "delegate to another generator" mean? How can I use yield* to "conveniently compose generators"?

[您可以使用 --harmony-generators 标志在 Node v0.11.3 中使用生成器.]

[You can play with generators in Node v0.11.3 with the --harmony-generators flag.]

推荐答案

委托给另一个生成器意味着当前生成器停止自己生成值,而是生成另一个生成器生成的值,直到它耗尽为止.然后它会继续生成自己的值(如果有).

Delegating to another generator means the current generator stops producing values by itself, instead yielding the values produced by another generator until it exhausts it. It then resumes producing its own values, if any.

例如,如果 secondGenerator() 产生从 1015 的数字,并且 firstGenerator() 产生从15的数字,但是在产生2后委托给secondGenerator(),然后由firstGenerator() 将是:

For instance, if secondGenerator() produces numbers from 10 to 15, and firstGenerator() produces numbers from 1 to 5 but delegates to secondGenerator() after producing 2, then the values produced by firstGenerator() will be:

1, 2, 10, 11, 12, 13, 14, 15, 3, 4, 5

function* firstGenerator() {
    yield 1;
    yield 2;
    // Delegate to second generator
    yield* secondGenerator();
    yield 3;
    yield 4;
    yield 5;
}

function* secondGenerator() {
    yield 10;
    yield 11;
    yield 12;
    yield 13;
    yield 14;
    yield 15;
}

console.log(Array.from(firstGenerator()));

这篇关于生成器函数中的委托产量(产量星,产量*)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆