这就是generator function 的工作原理。首先,您必须调用生成器函数,即GeneratorFunction,它将为您提供iterator 对象。
var gen = GeneratorFunction(3);
当您调用 gen(返回的迭代器对象) 的 next 函数时,将返回一个可以包含 2 个属性的对象,即 value 或 done
value 属性包含迭代的值,done 告诉我们是否可以从gen 获得更多值。
示例 在下面的 sn-p 中,当您调用 iterator 的 next 方法时,它会生成一个对象,其中您的值在 value 属性中,done 显示是否您可以从generator function 获得更多价值。
在done 为true 之后,无论您调用多少次next 方法,所有值都将为undefined
function* GeneratorFunction(i) {
yield 1;
yield 2;
yield 3;
}
var gen = GeneratorFunction(1);
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
注意:大多数情况下,您使用 generator function 和 for..of 循环,这将直接为您提供值
function* GeneratorFunction(i) {
yield 1;
yield 2;
yield 3;
}
var gen = GeneratorFunction(1);
for (let val of gen) {
console.log(val);
}
更新:函数调用
当你调用生成器函数时
var gen = GeneratorFunction(3);
它将i 的值作为3 传递,并且生成器函数的调用开始直到第一个yield 和生成器函数挂起并产生值:
{ value: 3, done: false }
由于done 是false,所以生成器函数负责并以1 的输入值重新开始,这将替换yield,它与以下内容相同:
i += yield i; // same as i += 1;
而i的值现在是4,不满足while循环的条件,退出循环。
之后
return i;
将对象返回为
{ value: 4, done: true }
如果生成器函数返回一个值,那么最后调用next
返回一个同时定义了value 和done 的对象。价值
属性保存生成器函数的返回值,并且
done属性为true,表示没有更多的值
迭代。
在done 是true 之后,进一步的调用将返回value 作为undefined 和done 作为true。
我更改了 sn-p 以将生成器函数的返回值简化为
function* GeneratorFunction(i) {
while (i < 4) {
i += yield i;
}
return "final value";
}
var gen = GeneratorFunction(3);
console.log(gen.next(1));
console.log(gen.next(1));
console.log(gen.next(1));
console.log(gen.next(1));
console.log(gen.next(1));
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }