--- title: Generator slug: Web/JavaScript/Reference/Global_Objects/Generator tags: - ECMAScript 2015 - Generator - JavaScript - Legacy Generator - Legacy Iterator - 参考 - 生成器 translation_of: Web/JavaScript/Reference/Global_Objects/Generator ---
生成器对象是由一个 {{jsxref("Statements/function*", "generator function", "", 1)}} 返回的,并且它符合可迭代协议和迭代器协议。
function* gen() {
yield 1;
yield 2;
yield 3;
}
let g = gen();
// "Generator { }"
function* idMaker(){
let index = 0;
while(true)
yield index++;
}
let gen = idMaker(); // "Generator { }"
console.log(gen.next().value);
// 0
console.log(gen.next().value);
// 1
console.log(gen.next().value);
// 2
// ...
Firefox (SpiderMonkey) 在 JavaScript 1.7 中也实现了一个较早版本的生成器,其中函数声明中的星号(*)不是必需的 (只需在函数体中使用yield 关键字)。但是,旧式生成器已弃用。不要使用它们;他们将被删除 ({{bug(1083482)}})。
Generator.prototype.next() {{non-standard_inline}}Generator.prototype.close() {{non-standard_inline}}next()函数时将会抛出 {{jsxref("StopIteration")}} 错误. 与ES2015 生成器对象的return()方法对应..Generator.prototype.send() {{non-standard_inline}}send(x) 对应于ES2015生成器对象中的 next(x)Generator.prototype.throw() {{non-standard_inline}}function fibonacci() {
var a = yield 1;
yield a * 2;
}
var it = fibonacci();
console.log(it); // "Generator { }"
console.log(it.next()); // 1
console.log(it.send(10)); // 20
console.log(it.close()); // undefined
console.log(it.next()); // throws StopIteration (as the generator is now closed)
| Specification | Status | Comment |
|---|---|---|
| {{SpecName('ES2015', '#sec-generator-objects', 'Generator objects')}} | {{Spec2('ES2015')}} | Initial definition. |
| {{SpecName('ESDraft', '#sec-generator-objects', 'Generator objects')}} | {{Spec2('ESDraft')}} |
{{Compat("javascript.builtins.Generator")}}