在线文档教程

yield*

yield*

yield*用于委托给另一个generator或迭代的对象。

语法

yield* [[expression]];

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

描述

yield*在操作数迭代表达,并产生通过将其返回的每个值。

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

示例

委托给另一台发生器

在下面的代码中,所产生的值g1()是从next()调用返回的,就像那些被调用的那些调用一样g2()

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}

其他Iterable对象

除了生成器对象外,yield*还可以使用yield其他类型的迭代器,例如数组,字符串或参数对象。

function* g3() { yield* [1, 2]; yield* '34'; yield* Array.from(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* 是一个表达式,而不是一个语句,因此它的计算结果是一个值。

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() returned {value: 'foo', done: true} at this point console.log(result // "foo"

规范

SpecificationStatusComment
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Yield' in that specification.StandardInitial definition.
ECMAScript Latest Draft (ECMA-262)The definition of 'Yield' in that specification.Living Standard

浏览器兼容性

FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support(Yes)(Yes)27.0 (27.0)??10

FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support(Yes)(Yes)27.0 (27.0)??10