js生成器中next的使用

319次阅读
没有评论

js生成器中next的使用

说明

1、生成器函数的外部可以向next方法传达参数,该参数作为上一个yield表现的返回值。

2、如果不传递参数,yield表达式返回undefined。

实例

const canBeStoppedCounter = (function* () {
  let c = 0;
  let shouldBreak = false;
  while (true) {
    shouldBreak = yield ++c;
    console.log(shouldBreak);
    if (shouldBreak) return;
  }
};
 
canBeStoppedCounter.next();
// { value: 1, done: false }
 
canBeStoppedCounter.next();
// undefined,第一次执行 yield 表达式的返回值
// { value: 2, done: false }
 
canBeStoppedCounter.next(true);
// true,第二次执行 yield 表达式的返回值
// { value: undefined, done: true }

以上就是js生成器中next的使用,希望对大家有所帮助。更多js学习指路:js教程

推荐操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:JavaScript2022-12-16发表,共计585字。
新手QQ群:570568346,欢迎进群讨论 Python51学习