return()
method returns the given value and finishes the generator.
gen.return(value)
value
The value to return.
The value that is given as an argument.
return()
The following example shows a simple generator and the
return
方法。
function* gen() {
yield 1;
yield 2;
yield 3;
}
const g = gen();
g.next(); // { value: 1, done: false }
g.return('foo'); // { value: "foo", done: true }
g.next(); // { value: undefined, done: true }
若
return(
value
)
is called on a generator that is already in "completed" state, the generator will remain in "completed" state.
If no argument is provided, the
value
property of returned object is the same as if
.next()
. If an argument is provided, it will be set to the value of the
value
property of the returned object.
function* gen() {
yield 1;
yield 2;
yield 3;
}
const 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 }
| 规范 |
|---|
|
ECMAScript (ECMA-262)
The definition of 'Generator.prototype.return' in that specification. |
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 |
完整支持
不支持
Generator
Generator.prototype.next()
Generator.prototype.return()
Generator.prototype.throw()
Function
Object
Object.prototype.__defineGetter__()
Object.prototype.__defineSetter__()
Object.prototype.__lookupGetter__()
Object.prototype.__lookupSetter__()
Object.prototype.hasOwnProperty()
Object.prototype.isPrototypeOf()
Object.prototype.propertyIsEnumerable()
Object.prototype.toLocaleString()
Object.prototype.toSource()
Object.prototype.toString()
Object.prototype.valueOf()
Object.setPrototypeOf()