Generator 函数是一个普通函数,但是有两个特征。一是,function关键字与函数名之间有一个星号;二是,函数体内部使用yield表达式,定义不同的内部状态(yield在英语里的意思就是“产出”):
function * myFun() {
console.log(1);
yield 1;
console.log(2);
yield 2;
console.log(3);
yield 3;
}
const result = myFun();
console.log(result.next());
console.log(result.next());
console.log(result.next());
console.log(result.next());
输出:
Generator 函数是分段执行的,yield表达式是暂停执行的标记,而next方法可以恢复执行。
---------------------------------------------------------------------------------------------------------------------------------
Generator 函数实现ID生成器:
function* crateIdMaker() {
let id = 1;
while (true) {
yield id++;
}
}
const idMaker = crateIdMaker();
console.log(idMaker.next().value);
console.log(idMaker.next().value);
console.log(idMaker.next().value);
console.log(idMaker.next().value);
console.log(idMaker.next().value);
console.log(idMaker.next().value);
// 1
// 2
// 3
// 4
// 5
// 6
---------------------------------------------------------------------------------------------------------------------------------
Generator 函数实现可迭代接口:
const lists = {
names: ['zs', 'ls', 'ww'],
hobbies: ['sing', 'reading'],
work: ['administration'],
[Symbol.iterator]: function * () {
const all = [...this.names, ...this.hobbies, ...this.work];
for (const item of all) {
yield item;
}
}
}
for (const item of lists) {
console.log(item);
}
输出: