ES6——Generator函数

本文深入探讨了ES6中的Generator函数,包括next方法的使用、for...of循环、异步读取、throw方法处理异常、return方法手动结束遍历、Generator的嵌套以及this的相关特性。还介绍了如何通过Thunk转换多参数为单参数,以便更好地理解和应用Generator函数。
摘要由CSDN通过智能技术生成


Generator 函数是 ES6 提供的一种 异步编程解决方案
(Generator 函数是一个状态机,封装了多个内部状态)

Generator 函数就是遍历器生成函数

function* 名称
体内 yield 表达式(状态等待执行 并返回)

一、next()方法

1.next不带参

    function* fun(){
   
        yield 1+1;
        yield 2+2;
        yield 3+3;
        yield 4+4;
        return 10;   //替换最终的value:undefined
    }
    //执行该函数
    let f=fun(); //执行之后返回遍历器
    console.log(f.next()); //{value: 2, done: false}
    console.log(f.next()); //{value: 4, done: false}
    console.log(f.next()); //{value: 6, done: false}
    console.log(f.next()); //{value: 8, done: false}
    console.log(f.next()); //{value: 10, done: true} 
    //不加return,value:undefined

在这里插入图片描述

2.next带参

参数指的是上一次yeild表达式的返回值 (本身是undefined)

    //next遍历带参 参数指的是上一次yeild表达式的返回值(本身是undefined)
    function* method(){
   
        let x=yield 1+2;
        console.log(x);
        let y=yield 3+x;
        console.log(y);
        return y+10;
    }
    let met=method();
    console.log(met.next()); //{value: 3, done: false}
    console.log(met.next(3)); //3  {value: 6, done: false}
    console.log(met.next(8)); //8  {value: 18, done: true}

3.面试题

(1)yield表达式如果用在另一个表达式之中,必须放在圆括号里面

    function* fun(){
   
        let x=yield 5+(yield 1+2);
        return x;
    }
    let xf=fun();
    console.log(xf.next()); //{value: 3, done: false}
    console.log(xf.next()); //{value: NaN, done: false}  (5+undefined)
    console.log
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

致可乐

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

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

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

打赏作者

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

抵扣说明:

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

余额充值