We're looking for a user researcher to understand the needs of developers and designers. Is this you or someone you know? Check out the post: https://mzl.la/2IGzdXS

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) 会和上次的 next() 一样,value 为 undefined.

function* gen() {yield 1;}
var g = gen();
console.log(g.next());//{ value: 1, done: false }
console.log(g.next());//{ value: undefined, done: true }
console.log(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  

浏览器兼容性

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support ? 38 (38) ? ? ?
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? ? 38.0 (38) ? ? ?

相关链接

文档标签和贡献者

此页面的贡献者: ljxy, Ende93, lukywong
最后编辑者: ljxy,