return() 方法返回给定的值并结束生成器。
语法
gen.return(value)
参数
-
value - 需要返回的值
返回值
返回该函数参数中给定的值.
示例
使用 return()
以下例子展示了一个简单的生成器和 return 方法的使用.
function* gen() {
yield 1;
yield 2;
yield 3;
}
var g = gen();
g.next(); // { value: 1, done: false }
g.return("foo"); // { value: "foo", done: true }
g.next(); // { value: undefined, done: true }
如果对已经处于“完成”状态的生成器调用return(value),则生成器将保持在“完成”状态。如果没有提供参数,则返回对象的value属性与示例最后的.next()方法相同。如果提供了参数,则参数将被设置为返回对象的value属性的值。
function* gen() {
yield 1;
yield 2;
yield 3;
}
var g = gen();
g.next(); // { value: 1, done: false }
g.next(); // { value: 2, done: false }
g.next(); // { value: 3, done: false }
g.next(); // { value: undefined, done: true }
g.return(); // { value: undefined, done: true }
g.return(1); // { value: 1, done: true }
规范
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) Generator.prototype.return |
Standard | Initial definition. |
| ECMAScript Latest Draft (ECMA-262) Generator.prototype.return |
Draft |
浏览器兼容性
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out
https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
return |
Chrome Full support 50 | Edge Full support 13 | Firefox Full support 38 | IE No support No | Opera Full support 37 | Safari Full support 10 | WebView Android Full support 50 | Chrome Android Full support 50 | Firefox Android Full support 38 | Opera Android Full support Yes | Safari iOS Full support 10 | Samsung Internet Android Full support 5.0 | nodejs Full support 6.0.0 |
Legend
- Full support
- Full support
- No support
- No support