ja_JavaScript_生成器
2022/2/25 22:24:13
本文主要是介绍ja_JavaScript_生成器,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
生成器
什么是生成器
yield的返回值
- yield后面的返回值,返回到调用next()返回的对象的value里面
生成器.return()代码提前终止执行
- return()实现代码的提前终止执行
生成器代替迭代器
生成器代替迭代器-方式一
03_生成器代替迭代器.js
关键代码
对比
function makeIterator(array) { let nextIndex = 0; return { next: function () { return nextIndex < array.length ? { value: array[nextIndex++], done: false } : { value: undefined, done: true }; }, }; } const it = makeIterator(['a', 'b']); console.log(it.next()); //=> { value: 'a', done: false } console.log(it.next()); //=> { value: 'b', done: false } console.log(it.next()); //=> { value: undefined, done: true } console.log('------------------------------------------------'); // ---------------------------------------------------- function* makeGenerator(array) { for (const item of array) { yield item; } } const gt = makeGenerator(['a', 'b']); console.log(gt.next()); //=> { value: 'a', done: false } console.log(gt.next()); //=> { value: 'b', done: false } console.log(gt.next()); //=> { value: undefined, done: true }
生成器代替迭代器-方式二
04_生成器代替迭代器_方式二.js
function* makeGenerator(array) { yield* array; } const gt = makeGenerator(['a', 'b']); console.log(gt.next()); //=> { value: 'a', done: false } console.log(gt.next()); //=> { value: 'b', done: false } console.log(gt.next()); //=> { value: undefined, done: true }
总结
- 三种写法
- 自己手动操作,一步一步计算,不推荐
- 使用for...of...循环遍历,推荐
- 语法糖形式,推荐
类中使用生成器代替迭代器
代码对比
关键代码
class Classroom { constructor(address, name, students) { this.address = address; this.name = name; this.students = students; } *[Symbol.iterator]() { yield* this.students; } } const c1 = new Classroom('Beijing', 'Xuexi', ['Alice', 'Bruce', 'Celina']); const iterator = c1[Symbol.iterator](); console.log(iterator.next()); //=> { done: false, value: 'Alice' } console.log(iterator.next()); //=> { done: false, value: 'Bruce' } console.log(iterator.next()); //=> { done: false, value: 'Celina' } console.log(iterator.next()); //=> { done: true, value: undefined } console.log('------------------'); for (let item of c1) { console.log(item); //=> Alice //=> Bruce //=> Celina }
生成器函数的自动执行
- 采用的是递归调用的思路
- 采用第三方co包,可以模拟上面的代码
这篇关于ja_JavaScript_生成器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-04TiDB 资源管控的对撞测试以及最佳实践架构
- 2024-07-03万字长文聊聊Web3的组成架构
- 2024-07-02springboot项目无法注册到nacos-icode9专业技术文章分享
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现