ECMAScript 6 应该引入生成器函数和迭代器。生成器函数(具有 function*
语法)返回迭代器。迭代器有一个 next
方法,当重复调用时,它会执行生成器函数的主体,在每个 yield
运算符处重复暂停和恢复执行。
ECMAScript 6 wiki on generators还引入了“委托(delegate) yield ”yield*
运算符,如下所示:
The
yield*
operator delegates to another generator. This provides a convenient mechanism for composing generators.
“委托(delegate)给另一个生成器”是什么意思?如何使用 yield*
来“方便地编写生成器”?
[您可以使用 --harmony-generators
标志在 Node v0.11.3 中使用生成器。]
最佳答案
Delegating to another generator 意味着当前的生成器停止自己产生值,而是产生由另一个生成器产生的值,直到它耗尽它。然后它会恢复生成自己的值(如果有的话)。
例如,如果 secondGenerator()
生成从 10
到 15
的数字,而 firstGenerator()
生成从 1
到 5
的数字,但在生成 2
之后委托(delegate)给 secondGenerator()
,然后 生成的值>firstGenerator()
将是:
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()));
关于javascript - 生成器函数中的委托(delegate) yield (yield star, yield *),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17491779/