/**
* 一个Generator函数 是一个状态机,封装多个内部状态
* 返回 : 一个遍历器对象,可以依次遍历 Generator 函数内部的每一个状态。
* 形式上: 1.function* 2.函数内部使用yield表达式 (暂停执行的标记)
* 区别于普通函数:调用 Generator 函数后,该函数并不执行,返回的也不是函数运行结果,而是一个指向内部状态的指针对象
*/
function* helloWorldGenerator() {
yield "hello";
yield "world";
return "ending";
}
let hw = helloWorldGenerator();
/**
* next 移动指针 直到遇到yield表达式或return语句
* value 是当前yield表达式的值
*/
hw.next(); // {value: 'hello',done: false}
hw.next(); // {value: 'world',done: false}
hw.next(); // {value: 'ending',done: true}
hw.next(); // {value: undefined,done: true}
let myIterable = {};
myIterable[Symbol.iterator] = function*() {
yield 1;
yield 2;
yield 3;
};
[...myIterable];
/**
* next方法的参数
* yield表达式本身没有返回值
* next方法可以带一个参数,该参数就会被当作上一个yield表达式的返回值。
* 用途:可以在 Generator 函数运行的不同阶段,从外部向内部注入不同的值,从而调整函数行为
*/
function* f() {
for (let i = 0; true; i++) {
let reset = yield i;
if (reset) {
i = -1;
}
}
}
let g = f();
g.next(); // {value: 0,done: false}
g.next(); // {value: 1,done: false}
g.next(true); // {value: 0,done: false}
/**
* for...of 循环
* 一旦next返回的对象的done为true时,for...of循环就会终止
*/
function* foo() {
yield 1;
yield 2;
yield 3;
return 4;
}
for (const v of foo()) {
console.log(v);
}
ES6的Generator函数
最新推荐文章于 2023-04-20 23:41:30 发布