function*关键字可以在表达式内部定义一个生成器函数。
语法
function* [name]([param1[, param2[, ..., paramN]]]) {
statements
}
参数
name- 函数名。在声明匿名函数时可以省略。函数名称只是函数体中的一个本地变量。
paramN- 传入函数的一个参数名。一个函数最多有 255 个参数。
statements- 函数体。
描述
function*表达式和function* 声明比较相似,并具有几乎相同的语法。function*表达式和function*声明之间主要区别就是函数名,即在创建匿名函数时,function*表达式可以省略函数名。阅读函数章节了解更多信息。
示例
下面的示例定义了一个未命名的生成器函数并把它赋值给x。函数产出它的传入参数的平方:
var x = function*(y) {
yield y * y;
};
规范
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) function* |
Standard | Initial definition. |
| ECMAScript Latest Draft (ECMA-262) function* |
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 | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
function* | Chrome Full support Yes | Edge Full support Yes | Firefox Full support 26 | IE No support No | Opera Full support Yes | Safari Full support 10 | WebView Android Full support Yes | Chrome Android Full support Yes | Edge Mobile Full support Yes | Firefox Android Full support 26 | Opera Android Full support Yes | Safari iOS Full support 10 | Samsung Internet Android Full support Yes | nodejs Full support Yes |
| Trailing comma in parameters | Chrome Full support 58 | Edge ? | Firefox Full support 52 | IE No support No | Opera Full support 45 | Safari ? | WebView Android Full support 58 | Chrome Android Full support 58 | Edge Mobile ? | Firefox Android Full support 52 | Opera Android Full support 45 | Safari iOS ? | Samsung Internet Android Full support 7.0 | nodejs Full support 8.0.0 |
Legend
- Full support
- Full support
- No support
- No support
- Compatibility unknown
- Compatibility unknown