Generator

Generator 对象的返回由 generator 函数 且它同时符合 可迭代协议 迭代器协议 .

构造函数

此对象不能直接实例化。相反, Generator 实例可以返回来自 generator 函数 :

function* generator() {
  yield 1;
  yield 2;
  yield 3;
}
const gen = generator(); // "Generator { }"
					

实例方法

Generator.prototype.next()
Returns a value yielded by the yield 表达式。
Generator.prototype.return()
Returns the given value and finishes the generator.
Generator.prototype.throw()
Throws an error to a generator (also finishes the generator, unless caught from within that generator).

范例

无限迭代器

function* infinite() {
    let index = 0;
    while (true) {
        yield index++;
    }
}
const generator = infinite(); // "Generator { }"
console.log(generator.next().value); // 0
console.log(generator.next().value); // 1
console.log(generator.next().value); // 2
// ...
					

规范

规范
ECMAScript (ECMA-262)
The definition of 'Generator objects' in that specification.

浏览器兼容性

更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
Generator Chrome 39 Edge 13 Firefox 26 IE No Opera 26 Safari 10 WebView Android 39 Chrome Android 39 Firefox Android 26 Opera Android 26 Safari iOS 10 Samsung Internet Android 4.0 nodejs 4.0.0
4.0.0
0.12
Disabled
Disabled From version 0.12: this feature is behind the --harmony runtime flag.
next Chrome 39 Edge 13 Firefox 26 IE No Opera 26 Safari 10 WebView Android 39 Chrome Android 39 Firefox Android 26 Opera Android 26 Safari iOS 10 Samsung Internet Android 4.0 nodejs Yes
return Chrome 50 Edge 13 Firefox 38 IE No Opera 37 Safari 10 WebView Android 50 Chrome Android 50 Firefox Android 38 Opera Android 37 Safari iOS 10 Samsung Internet Android 5.0 nodejs 6.0.0
throw Chrome 39 Edge 13 Firefox 26 IE No Opera 26 Safari 10 WebView Android 39 Chrome Android 39 Firefox Android 26 Opera Android 26 Safari iOS 10 Samsung Internet Android 4.0 nodejs 4.0.0
4.0.0
0.12
Disabled
Disabled From version 0.12: this feature is behind the --harmony runtime flag.

图例

完整支持
完整支持
不支持
不支持
用户必须明确启用此特征。
用户必须明确启用此特征。

另请参阅

Metadata