Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

Generator

BaselineWidely available

Generator オブジェクトはジェネレーター関数によって返され、反復可能プロトコルイテレータープロトコルの両方に準拠しています。

試してみましょう

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"

コンストラクター

このオブジェクトを直接インスタンス化することはできません。代わりに、ジェネレーター関数からGenerator のインスタンスを返すことができます。

function* generator() {  yield 1;  yield 2;  yield 3;}const gen = generator(); // "Generator { }"

インスタンスメソッド

Generator.prototype.next()

yield 式で得られた値を返します。

Generator.prototype.return()

与えられた値を返し、ジェネレーターを終了します。

Generator.prototype.throw()

ジェネレーターにエラーを投げます。(そのジェネレーターの中からキャッチされない限り、ジェネレーターも終了します)

無限イテレーター

js
function* infinite() {  let index = 0;  while (true) {    yield index++;  }}const generator = infinite(); // "Generator { }"console.log(generator.next().value); // 0console.log(generator.next().value); // 1console.log(generator.next().value); // 2// ...

仕様書

Specification
ECMAScript® 2026 Language Specification
# sec-generator-objects

ブラウザーの互換性

関連情報

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp