【发布时间】:2018-01-23 22:26:43
【问题描述】:
我偶然发现了generator functions on MDN,令我困惑的是以下示例:
function* logGenerator() {
console.log(yield);
console.log(yield);
console.log(yield);
}
var gen = logGenerator();
// the first call of next executes from the start of the function
// until the first yield statement
gen.next();
gen.next('pretzel'); // pretzel
gen.next('california'); // california
gen.next('mayonnaise'); // mayonnaise
我不明白为什么yield 语句是console.log 的参数,它返回传递给生成器的.next() 方法的参数。这是因为空的yield 必须返回.next() 方法的第一个参数的值吗?
我也尝试了更多的例子,这似乎证实了上面的说法:
gen.next(1,2,3); // the printed value is 1, the 2 and 3 are ignored
// and the actual yielded value is undefined
还有没有办法访问生成器函数体内.next() 方法的更多参数?
我注意到的另一件事是,当 yield 语句将这些值返回到 console.log 时,它们实际上并没有作为生成器的输出而产生。我必须说我觉得这很混乱。
【问题讨论】:
-
...因为这就是应该发生的事情?为什么这让你感到困惑?
-
这就是
yield表达式的计算结果。 -
@user2357112 它让我感到困惑,因为我没有看到上面代码中要引用的参数。阅读了答案中的链接后,现在一切都说得通了,但是当我第一次看到它时,我并不理解。作为旁注,您还可以执行
function* x() {yield yield yield;}之类的操作
标签: javascript yield