js生成器中next的使用方法
更新:HHH   时间:2023-1-7


本篇内容主要讲解“js生成器中next的使用方法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“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的使用方法”有了更深的了解,不妨来实际操作一番吧!这里是天达云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

返回编程语言教程...