ES6的Generator函数

/**
 * 一个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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值