ES6-Generator基础用法
2024-09-01 10:26:42
Generator简介:
生成器,本身是函数,执行后返回迭代对象,函数内部要配合yield使用Generator函数会分段执行,遇到yield暂停。
使用Generator注意点:function 和函数名之间需要带 *
function* text(){ }
Generator的yield注意点:yield是ES6新关键字,作用是使Generator(生成器)函数暂停。
function* text(){
yield 'a';
yield 'b';
yield 'c';
return 'd';
}
let iterationObj = text(); console.log(iterationObj.next());//{value: "a", done: false}
console.log(iterationObj.next());//{value: "b", done: false}
console.log(iterationObj.next());//{value: "c", done: false}
console.log(iterationObj.next());//{value: "d", done: true} yield后,必须return最后一个值,如果不return最后一个值value为undefined。 当每次执行后返回{value, done}value值是当次执行yield里面的值,done值是当次执行看看代码执行到第几行,如果到最后一行返回true,其他返回false
那么我们如何证明当遇到yield函数暂停。
function* text(){
yield 'a';
console.log('1');
yield 'b';
console.log('2');
yield 'c';
console.log('3');
return 'd'
} let iterationObj = text();
console.log(iterationObj.next());//因为第一行是yield碰到暂停输出:{value: "a", done: false}
console.log(iterationObj.next());//执行第二行输出:1 然后碰到yield暂停输出:{value: "b", done: false}
当yield被变量接收,下一次执行参数就是上一个变量的值。
function* text(){
let value = yield 'a';
console.log(value);
let value1 = yield 'b';
console.log(value1);
let value2 = yield 'c';
console.log(value2);
return 'd'
} let iterationObj = text();
console.log(iterationObj.next());//{value: "a", done: false} 因为第一个是执行yield所以直接暂停不输出第二行的console.log
console.log(iterationObj.next('22'));
那么打印结果就是{value: "a", done: false}
22
{value: "b", done: false}
最新文章
- UITableViewHeaderFooterView的封装
- WebApi Put方法出现MethodNotAllowed解决方法
- Delphi 操作Word怎么控制光标的位置
- 复习C语言
- Swift内存管理-示例讲解
- 14.6.3.5 Configuring InnoDB Buffer Pool Flushing
- Android - Service启动机制
- Python之路第十一天,高级(3)-线程池
- <;转>;shell经典,shell十三问
- windows系统 docker + swoole 操作
- selenium 使用
- 《剑指offer》第六十五题(不用加减乘除做加法)
- Linux命令:ssh-copy-id
- 57.storm拓扑结构调整
- mysql提示Fatal error: Can&#39;t open and lock privilege tables: Table &#39;mysql.host&#39; doesn&#39;t exist解决方法
- zabbix添加对tomcat线程池的监控
- iOS7,iOS8和iOS9的区别
- 公共的Json操作类
- Spring MVC No converter found for return value of type 解决方法
- 将xml转为array
热门文章
- 单片机成长之路(51基础篇) - 026 基于stm89c52之单片机看门狗
- .net 6.0 新特性
- c#实现串口通信
- mini QQ(项目一)
- C# - Winform - DevExpress - GridControl 任意条件控制Row背景色。
- js 数组去重总结
- docker 部署mysql redis
- Oracle自定义脱敏函数
- sudo: /usr/lib/sudo/sudoers.so must be only be writable by owner
- nginx 配置相关解析