function* 表达式

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2016.

function* 关键字可以在表达式内部定义一个生成器函数。

尝试一下

const foo = function* () {
  yield "a";
  yield "b";
  yield "c";
};

let str = "";
for (const val of foo()) {
  str = str + val;
}

console.log(str);
// Expected output: "abc"

语法

function* [name]([param1[, param2[, ..., paramN]]]) {
   statements
}

参数

name

函数名。在声明匿名函数时可以省略。函数名称只是函数体中的一个本地变量。

paramN

传入函数的一个参数名。一个函数最多有 255 个参数。

statements

函数体。

描述

function*表达式和function* 声明比较相似,并具有几乎相同的语法。function*表达式和function*声明之间主要区别就是函数名,即在创建匿名函数时,function*表达式可以省略函数名。阅读函数章节了解更多信息。

示例

下面的示例定义了一个未命名的生成器函数并把它赋值给x。函数产出它的传入参数的平方:

js
var x = function* (y) {
  yield y * y;
};

规范

Specification
ECMAScript® 2025 Language Specification
# sec-generator-function-definitions

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
function* expression
Trailing comma in parameters

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见