--- title: yield slug: Web/JavaScript/Reference/Operators/yield tags: - ECMAScript 2015 - Generators - Iterator - JavaScript - Operator translation_of: Web/JavaScript/Reference/Operators/yield ---
yield
关键字用来暂停和恢复一个生成器函数(({{jsxref("Statements/function*", "function*")}} 或遗留的生成器函数)。
[rv] = yield [expression];
expression
undefined
。rv
返回传递给生成器的next()
方法的可选值,以恢复其执行。
yield
关键字使生成器函数执行暂停,yield
关键字后面的表达式的值返回给生成器的调用者。它可以被认为是一个基于生成器的版本的return
关键字。
yield
关键字实际返回一个IteratorResult
对象,它有两个属性,value
和done
。value
属性是对yield
表达式求值的结果,而done
是false
,表示生成器函数尚未完全完成。
一旦遇到 yield
表达式,生成器的代码将被暂停运行,直到生成器的 next()
方法被调用。每次调用生成器的next()
方法时,生成器都会恢复执行,直到达到以下某个值:
yield
,导致生成器再次暂停并返回生成器的新值。 下一次调用next()
时,在yield
之后紧接着的语句继续执行。IteratorResult
给调用者返回{{jsxref("undefined")}}并且done
为true
。IteratorResult
返回给调用者,其值是由return
语句指定的,并且done
为true
。如果将参数传递给生成器的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")}}