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}

  

最新文章

  1. UITableViewHeaderFooterView的封装
  2. WebApi Put方法出现MethodNotAllowed解决方法
  3. Delphi 操作Word怎么控制光标的位置
  4. 复习C语言
  5. Swift内存管理-示例讲解
  6. 14.6.3.5 Configuring InnoDB Buffer Pool Flushing
  7. Android - Service启动机制
  8. Python之路第十一天,高级(3)-线程池
  9. <转>shell经典,shell十三问
  10. windows系统 docker + swoole 操作
  11. selenium 使用
  12. 《剑指offer》第六十五题(不用加减乘除做加法)
  13. Linux命令:ssh-copy-id
  14. 57.storm拓扑结构调整
  15. mysql提示Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist解决方法
  16. zabbix添加对tomcat线程池的监控
  17. iOS7,iOS8和iOS9的区别
  18. 公共的Json操作类
  19. Spring MVC No converter found for return value of type 解决方法
  20. 将xml转为array

热门文章

  1. 单片机成长之路(51基础篇) - 026 基于stm89c52之单片机看门狗
  2. .net 6.0 新特性
  3. c#实现串口通信
  4. mini QQ(项目一)
  5. C# - Winform - DevExpress - GridControl 任意条件控制Row背景色。
  6. js 数组去重总结
  7. docker 部署mysql redis
  8. Oracle自定义脱敏函数
  9. sudo: /usr/lib/sudo/sudoers.so must be only be writable by owner
  10. nginx 配置相关解析