ES6 Generator函数 yield与next的使用

Generator 函数概述

  1. 遇到yield表达式,就暂停执行后面的操作,并将yield表达式的值作为value
  2. 每次调用next方法,内部指针就从函数头部或上一次停下来的地方开始执行,直到遇到下一个yield表达式(或return语句)为止
  3. Generator 函数是分段执行的,yield表达式是暂停执行的标记,而next方法可以恢复执行

写法

  1. Generator 函数是一个普通函数,function关键字与函数名之间有一个星号
  2. ES6 没有规定,function关键字与函数名之间的星号,写在哪个位置。这导致下面的写法都能通过
function * foo(x, y) { ··· }
function *foo(x, y) { ··· }
function* foo(x, y) { ··· }
function*foo(x, y) { ··· }

代码示例

  • value:当前yield表达式的值
  • done:遍历是否已结束

function* helloWorldGenerator() {
    console.log(1)
    yield 'hello';

    console.log(2)
    yield 'world';

    console.log(3)
    return 'ending';
}
// 调用函数会返回一个遍历器对象
var hw = helloWorldGenerator();

hw.next()// { value: 'hello', done: false }
hw.next()// { value: 'world', done: false }
hw.next()// { value: 'ending', done: true }
hw.next()// { value: undefined, done: true }

执行解析

  1. 第1次next执行代码
console.log(1)
yield 'hello';
  1. 第2次next执行代码
console.log(2)
yield 'world';
  1. 第3次next执行代码
console.log(3)
return 'ending';
  1. 第4次next执行代码
    在第三次next时,done变为true,表示函数已经运行完毕
    第四次以及之后再调用next方法,返回的都是这个值{ value: undefined, done: true }
  • 17
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

来一颗砂糖橘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值