--- title: yield slug: Web/JavaScript/Reference/Operators/yield tags: - ECMAScript 2015 - Generators - Iterator - JavaScript - Operator translation_of: Web/JavaScript/Reference/Operators/yield ---
{{jsSidebar("Operators")}}

yield 关键字用来暂停和恢复一个生成器函数(({{jsxref("Statements/function*", "function*")}} 或遗留的生成器函数)。

语法

[rv] = yield [expression];
expression
定义通过迭代器协议从生成器函数返回的值。如果省略,则返回undefined
rv

返回传递给生成器的next()方法的可选值,以恢复其执行。

描述

yield关键字使生成器函数执行暂停,yield关键字后面的表达式的值返回给生成器的调用者。它可以被认为是一个基于生成器的版本的return关键字。

yield关键字实际返回一个IteratorResult对象,它有两个属性,valuedonevalue属性是对yield表达式求值的结果,而donefalse,表示生成器函数尚未完全完成。

一旦遇到 yield 表达式,生成器的代码将被暂停运行,直到生成器的 next() 方法被调用。每次调用生成器的next()方法时,生成器都会恢复执行,直到达到以下某个值:

如果将参数传递给生成器的next()方法,则该值将成为生成器当前yield操作返回的值。

在生成器的代码路径中的yield运算符,以及通过将其传递给{{jsxref("Generator.prototype.next()")}}指定新的起始值的能力之间,生成器提供了强大的控制力。

示例

以下代码是一个生成器函数的声明。

function* countAppleSales () {
  var saleList = [3, 7, 5];
  for (var i = 0; i < saleList.length; i++) {
    yield saleList[i];
  }
}

一旦生成器函数已定义,可以通过构造一个迭代器来使用它。

var appleStore = countAppleSales(); // Generator { }
console.log(appleStore.next()); // { value: 3, done: false }
console.log(appleStore.next()); // { value: 7, done: false }
console.log(appleStore.next()); // { value: 5, done: false }
console.log(appleStore.next()); // { value: undefined, done: true }

规范

Specification Status Comment
{{SpecName('ES2015', '#', 'Yield')}} {{Spec2('ES2015')}} Initial definition.
{{SpecName('ESDraft', '#', 'Yield')}} {{Spec2('ESDraft')}}  

浏览器兼容性

{{Compat("javascript.operators.yield")}}

相关链接