ES6 generator function* yiled*用法

本文深入解析了JavaScript中Generator函数的使用方法,包括function*关键字定义生成器函数,yield关键字的使用,以及yield*表达式用于委托给另一个generator或可迭代对象。通过实例展示了如何创建和使用Generator函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单叙述一下generator用法

function*关键字可以在表达式内部定义一个生成器函数。

function* foo() {
  yield 'a';
  yield 'b';
  yield 'c';
}

let str = '';
for (const val of foo()) {
  str = str + val;
}

console.log(str);  // "abc"

 yiled关键字用来暂停一个生成器函数

 function *play(num) {
        let index = num || 0;
        while(index < num + 2){
            yield ++index
        }
        return 10
    }

        let count = play(5);
    console.log(count.next()); // {value: 6, done: false}
    console.log(count.next()); // {value: 7, done: false}
    console.log(count.next()); // {value: 10, done: true} 结束

 yield* 表达式用于委托给另一个generator 或可迭代对象

    function *play(num) {
        let index = num || 0;
        while(index < num + 2){
            yield ++index
        }
        return 10
    }


    function *pause(num) {
        yield* play(num)
    }
    let p = pause(5);
    console.log(p.next()); // {value: 6, done: false}
    console.log(p.next()); // {value: 7, done: false}
    console.log(p.next()); // {value: undefined, done: true}

    function* g3() {
        yield* [1, 2];
        yield* "34";
        yield* arguments;
    }

    var iterator = g3(5, 6);
    console.log(iterator.next()); // {value: 1, done: false}
    console.log(iterator.next()); // {value: 2, done: false}
    console.log(iterator.next()); // {value: "3", done: false}
    console.log(iterator.next()); // {value: "4", done: false}
    console.log(iterator.next()); // {value: 5, done: false}
    console.log(iterator.next()); // {value: 6, done: false} 

yield* 是一个表达式,不是语句,所以它会有自己的值。

 function *play() {
        yield * [];
        return 10
    }
    var pause = play();
    console.log(pause.next());  // {value: 10, done: true}

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值