当前位置: 首页 > news >正文

【ES6】Generator 函数

Generator 函数是 ES6 引入的一种新的函数类型,它既可以生成一个序列,又可以在某个条件下停止执行,并在需要时恢复执行。Generator 函数非常适合处理那些需要按需计算的场景,例如处理大数据、生成随机数等。

Generator 函数的基本语法

Generator 函数的语法如下:

function* generator() {yield value1;yield value2;// ...
}

其中,* 是 Generator 函数的标识符,yield 是 Generator 函数的关键字,用于生成一个值。在 Generator 函数中,每个 yield 都会生成一个值并暂停执行,只有调用 Generator 函数的 next() 方法时才会继续执行。

使用 Generator 函数

下面是一个简单的例子,展示了如何使用 Generator 函数生成一个序列:

function* sequence() {let i = 1;while (true) {yield i++;}
}const sequenceGenerator = sequence();
console.log(sequenceGenerator.next()); // { value: 1, done: false }
console.log(sequenceGenerator.next()); // { value: 2, done: false }
console.log(sequenceGenerator.next()); // { value: 3, done: false }
// ...

在上面的例子中,我们定义了一个名为 sequence 的 Generator 函数,用于生成一个从 1 到无穷大的序列。在每次调用 next() 方法时,Generator 函数会生成下一个值并返回给调用者。

控制 Generator 函数的执行

除了通过 next() 方法控制 Generator 函数的执行外,我们还可以使用 return 语句来结束 Generator 函数的执行,并返回一个值:

function* generator() {yield 1;yield 2;return 3;
}const generatorObj = generator();
console.log(generatorObj.next()); // { value: 1, done: false }
console.log(generatorObj.next()); // { value: 2, done: false }
console.log(generatorObj.next()); // { value: 3, done: true }

在上面的例子中,我们在 Generator 函数的末尾使用了一个 return 语句,当调用第三次 next() 方法时,Generator 函数会返回 { value: 3, done: true },表示已经完成执行。

使用 for…of 循环遍历 Generator 函数生成的序列

除了使用 next() 方法遍历 Generator 函数生成的序列外,我们还可以使用 for…of 循环来遍历:

function* sequence() {let i = 1;while (true) {yield i++;}
}const sequenceGenerator = sequence();
for (let value of sequenceGenerator) {console.log(value); // 1, 2, 3, ...
}

在上面的例子中,我们使用 for…of 循环来遍历 Generator 函数生成的序列,每次输出当前的值。需要注意的是,for…of 循环无法判断 Generator 函数是否已经完成执行,因此如果 Generator 函数已经结束,那么 for…of 循环将无法继续执行。

http://www.lryc.cn/news/148457.html

相关文章:

  • 「操作系统」1. 基础
  • Docker安装Oracl数据库!
  • QT子窗口为QWidget类型时,窗口背景不透明的实现方法
  • leecode 数据库:1158. 市场分析 I
  • 简单shell脚本的编写
  • 汽车售后接待vr虚拟仿真实操演练作为岗位培训的重要工具和手段
  • 登录校验-Filter-登录校验过滤器
  • Vue3列表竖向滚动(包含使用swiper的翻页效果)
  • OS 死锁处理
  • Java实现根据按图搜索商品数据,按图搜索获取1688商品详情数据,1688拍立淘接口,1688API接口封装方法
  • 如何避免重复消费消息
  • 【若依框架RuoYi-Vue-Plus 图片回显不显示问题,OSS文件上传或者本地上传】
  • docker搭建rocketmq环境
  • uwsgi部署多进程django apscheduler与问题排查
  • git difftool对比差异,避免推送不相关内容
  • Java设计模式:一、六大设计原则-05:接口隔离原则
  • 第63步 深度学习图像识别:多分类建模误判病例分析(Tensorflow)
  • OpenCv读/写视频色差 方案
  • 【传输层】网络基础 -- UDP协议 | TCP协议
  • Android开发之性能测试工具Profiler
  • SpringBoot初级开发--多环境配置的集成(9)
  • (数学) 剑指 Offer 39. 数组中出现次数超过一半的数字 ——【Leetcode每日一题】
  • 如何用PS把roughness贴图转换成Smoothness,并放入Metallic贴图的a通道。
  • 了解XSS攻击与CSRF攻击
  • 安全测试-django防御安全策略
  • 7.react useReducer使用与常见问题
  • c#泛型(generic)
  • 【力扣每日一题】2023.8.30 到家的最少跳跃次数
  • 精读《算法题 - 地下城游戏》
  • 随记-Kibana Dev Tools,ES 增删改查 索引,Document