Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. JavaScript
  3. JavaScript 参考
  4. 表达式和运算符
  5. yield*

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

yield*

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2016年9月⁩.

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

语法

 yield* [[expression]];
expression

返回一个可迭代对象的表达式。

描述

yield* 表达式迭代操作数,并产生它返回的每个值。

yield* 表达式本身的值是当迭代器关闭时返回的值(即donetrue时)。

示例

委托给其他生成器

以下代码中,g1()yield 出去的每个值都会在g2()next() 方法中返回,就像那些yield 语句是写在g2() 里一样。

js
function* g1() {  yield 2;  yield 3;  yield 4;}function* g2() {  yield 1;  yield* g1();  yield 5;}var iterator = g2();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: undefined, done: true }

委托给其他可迭代对象

除了生成器对象这一种可迭代对象,yield* 还可以yield 其他任意的可迭代对象,比如说数组、字符串、arguments 对象等等。

js
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 }console.log(iterator.next()); // { value: undefined, done: true }

yield* 表达式的值

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

js
function* g4() {  yield* [1, 2, 3];  return "foo";}var result;function* g5() {  result = yield* g4();}var iterator = g5();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: undefined, done: true },// 此时 g4() 返回了 { value: "foo", done: true }console.log(result); // "foo"

规范

Specification
ECMAScript® 2026 Language Specification
# sec-generator-function-definitions-runtime-semantics-evaluation

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp