什么是生成器
生成器是一个通过构造函数 Generator 创建的对象,生成器既是一个迭代器,同时又是一个可迭代对象
如何创建生成器
生成器的创建,必须使用生成器函数(Generator Function)
如何书写一个生成器函数
// 这是一个生成器函数,该函数一定返回一个生成器
function* method() { }
生成器函数内部是如何执行的
生成器函数内部是为了给生成器的每次迭代提供数据
每次调用生成器的 next 方法,将导致生成器函数运行到下一个 yield 关键字为止
yield 是一个关键字,该关键字只能在生成器函数内部使用,表达“产生”一个迭代数据
举个例子
function* method() {
yield 1;
yield 2;
yield 3;
}

再举个例子,用生成器完成那个经典的斐波那契数列
function* createFeiboIterator() {
let prev1 = 1;
prev2 = 1;
n = 1;
while (true) {
if (n <= 2) {
yield 1;
} else {
const newValue = prev1 + prev2;
yield newValue;
prev2 = prev1;
prev1 = newValue;
}
n++;
}
}
const iterator = createFeiboIterator();

有哪些需要注意的细节
- 生成器函数可以有返回值,返回值出现在第一次 done 为 true 时的 value 属性中
function* method() {
yield 1;
yield 2;
yield 3;
return 4;
}
const iterator = method();

- 调用生成器的 next 方法时,可以传递参数,传递的参数会交给 yield 表达式的返回值
function* method() {
let info = yield 1;
console.log(info);
info = yield 2 + info;
console.log(info);
}
const iterator = method();

- 第一次调用 next 方法时,传参没有任何意义
- 再生成器的内部,可以调用其他生成器函数,但是要加 * 号
function* test1() {
yield 1;
yield 2;
}
function* test2() {
yield* test1()
yield 3;
yield 4;
}
const iterator = test2();

生成器其他 API
- return 方法:调用该方法,可以提前结束生成器函数,提前让整个迭代结束
- throw 方法:调用该方法,可以在生成器中产生一个错误
function* test() {
yield 1;
yield 2;
yield 3;
}
const iterator = test();


网友评论