Generator

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

コンストラクター

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

function* generator() {
  yield 1;
  yield 2;
  yield 3;
}

const gen = generator(); // "Generator { }"

インスタンスメソッド

Generator.prototype.next()

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

Generator.prototype.return()

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

Generator.prototype.throw()

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

無限イテレーター

function* infinite() {
    let index = 0;

    while (true) {
        yield index++;
    }
}

const generator = infinite(); // "Generator { }"

console.log(generator.next().value); // 0
console.log(generator.next().value); // 1
console.log(generator.next().value); // 2
// ...

仕様

Specification
ECMAScript Language Specification
# sec-generator-objects

ブラウザー実装状況

BCD tables only load in the browser

関連情報