JavaScript/Iterable Interface

カテゴリ:Book:JavaScript#Iterable%20Interface%20

The Iterable Interface は、オブジェクトが反復可能であることを示すインターフェースです。このインターフェースを実装するオブジェクトは、for...of ループなどのイテレーション操作で使用できます[1]

構文

[Symbol.iterator]() { /* ... */ }
  • [Symbol.iterator]: イテレータオブジェクトを返すメソッド。

反復可能オブジェクトを作成するプログラム

以下のプログラムは、Iterable インターフェースを実装して反復可能なオブジェクトを作成します。

const iterableObj = {
  data: [1, 2, 3, 4, 5],
  [Symbol.iterator]() {
    let index = 0;
    return {
      next: () => {
        if (index < this.data.length) {
          return { value: this.data[index++], done: false };
        } else {
          return { done: true };
        }
      }
    };
  }
};

for (const value of iterableObj) {
  console.log(value); // 1, 2, 3, 4, 5
}

このプログラムでは、Symbol.iterator メソッドを実装して反復可能なオブジェクトを作成しています。for...of ループを使用してオブジェクトを反復処理することができます。

組み込み反復可能オブジェクトを使用するプログラム

以下のプログラムは、JavaScriptの組み込み反復可能オブジェクトを使用します。

const str = "Hello";
const array = [1, 2, 3];
const map = new Map([["a", 1], ["b", 2]]);
const set = new Set([1, 2, 3]);

for (const char of str) {
  console.log(char); // "H", "e", "l", "l", "o"
}

for (const num of array) {
  console.log(num); // 1, 2, 3
}

for (const [key, value] of map) {
  console.log(key, value); // "a" 1, "b" 2
}

for (const item of set) {
  console.log(item); // 1, 2, 3
}

このプログラムでは、文字列、配列、Map、Setなどの組み込み反復可能オブジェクトを使用しています。これらのオブジェクトはIterableインターフェースを実装しているため、for...ofループで反復処理できます。

注意点

  • 反復可能オブジェクト: ArrayStringMapSetTypedArrayargumentsオブジェクトなどは組み込みの反復可能オブジェクトです。
  • カスタムイテラブル: Symbol.iteratorメソッドを実装することで、カスタムオブジェクトを反復可能にすることができます。
  • 無限イテラブル: 無限シーケンスを生成するイテラブルを作成することもできますが、無限ループを避けるために注意が必要です。

脚註

  1. これは、コレクションの要素を反復処理するために使用されます。

外部リンク

カテゴリ:Book:JavaScript#Iterable%20Interface%20 カテゴリ:JavaScript
カテゴリ:Book:JavaScript カテゴリ:JavaScript カテゴリ:Pages using the JsonConfig extension