ES6 Generator生成器

Generator函数是JavaScript中的一种特殊函数,它允许函数暂停执行并保存执行上下文。通过yield表达式,Generator可以生成一系列值,例如用于实现迭代器或者状态机。在给出的示例中,Generator被用来创建一个无限递增的ID生成器和实现一个可迭代的对象。通过调用next方法,可以按需获取Generator的下一个返回值。这种函数在处理异步操作和控制流程管理时非常有用。
摘要由CSDN通过智能技术生成

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);
}

输出:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值