我试图了解如何使用ES6 Generator函数。除了一个关于在传递参数时进行一个空的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的第一行,因此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
参考:Mozilla文档
好吧,生成器功能有点特殊。它们可以在执行过程中多次接受和返回值,而“常规”函数只能接受一组固定的参数,并返回单个值。在您的第一个示例中,它们用于将数据传递到生成器(多次传递参数),而在第二个示例中,它们用于相反的方式(多次返回值)。
考虑以下示例:
function* foo() {
console.log("before a");
var a = (yield 123);
console.log("after a");
yield (a * 2);
console.log("end of function");
}
var bar = foo();
var x = bar.next(); // Runs until the first yield, prints 'before a'.
console.log(x.value); // 123
var y = bar.next(4); // Runs until the second yield, so prints 'after a'.
console.log(y.value); // 8
var z = bar.next(); // prints 'end of function'.
console.log(z.done); // true
我们在第一个next()
调用中不传递任何数据,直到第一个yield
语句运行。由于yield 123
调用(x.value
)的结果为123。下一次我们next()
使用4
参数值进行调用时,将a
在生成器函数内填充局部变量。代码将执行到下yield
一条语句,并返回的结果8
。
有关为什么0
而不是的说明1
,请参见其他答案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句