扫码关注官方订阅号
一个*号的区别吗?
闭关修行中......
两者都是返回 iterator 的一个元素,不过
yield 的返回值是当作一个元素yield* 的返回值是一个 iterator,会依次返回这个 iterator 中的每个元素
function* sub() { for (let i = 65; i < 70; i++) { yield String.fromCharCode(i); } } function* main() { yield "begin"; yield sub(); // 返回的是 sub() 的结果,一个对象 yield "---------"; yield* sub(); // 依次返回 sub() 结果的的每一项 yield "end"; } for (var v of main()) { console.log(v); }
The yield keyword is used to pause and resume a generator function.The yield* expression is used to delegate to another generator or iterable object.
function* g1() { yield 2 yield 3 } function* g2() { yield 1 yield g1() yield* g1() yield [4, 5] yield* [6, 7] } const iterator = g2() console.log(iterator.next()) // { value: 1, done: false } console.log(iterator.next()) // { value: {}, done: false } console.log(iterator.next()) // { value: 2, done: false } console.log(iterator.next()) // { value: 3, done: false } console.log(iterator.next()) // { value: [4, 5], done: false } console.log(iterator.next()) // { value: 6, done: false } console.log(iterator.next()) // { value: 7, done: false } console.log(iterator.next()) // { value: undefined, done: true }
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
两者都是返回 iterator 的一个元素,不过
yield 的返回值是当作一个元素
yield* 的返回值是一个 iterator,会依次返回这个 iterator 中的每个元素
举例
The yield keyword is used to pause and resume a generator function.
The yield* expression is used to delegate to another generator or iterable object.