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"
構文
js
function* [name]([param1[, param2[, ..., paramN]]]) {
statements
}
引数
name
省略可-
関数名。省略可。省略した場合、関数は無名関数として認識されます。名前は関数本体のみにローカルです。
paramN
省略可-
関数に渡される引数の名前。関数は最大 255 個の引数を持つことができます。
statements
-
関数の本体を構成する文。
解説
function*
式は function* 文ととてもよく似ており、構文もほとんど同じです。function*
式と function*
文の主な違いは、function*
式で無名ジェネレーター関数を生成する場合は関数名が省略できる点です。詳細は functions
をご覧ください。
例
function* の使用
次の例では、無名ジェネレーター関数を定義し、x
に代入します。関数は引数の二乗を生成します。
js
let x = function* (y) {
yield y * y;
};
仕様書
Specification |
---|
ECMAScript® 2025 Language Specification # sec-generator-function-definitions |
ブラウザーの互換性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
function* expression | ||||||||||||||
Trailing comma in parameters |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
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.