【发布时间】:2017-02-05 13:26:03
【问题描述】:
我试图了解如何使用 ES6 生成器函数。除了在传递参数时进行空的 next() 函数调用这一概念之外,这似乎非常简单。这是我从 Mozilla 文档中引用的代码。
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 语句,因此没有返回任何内容,然后我们第二次调用 next(),代码执行到包含第一个 yield 行的第二个 yield,因此pretzel 已记录到控制台。
如果是这种情况,在下面提到的代码中,0 如何在第一次调用next() 时登录?我在这里遗漏了一些东西:(
function* idMaker() {
var index = 0;
while (index < 3)
yield index++;
}
var gen = idMaker();
console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // undefined
【问题讨论】:
-
“直到 yield 语句”的意思是“产生第一个值”。