ecmascript:iteration
差分
このページの2つのバージョン間の差分を表示します。
次のリビジョン | 前のリビジョン | ||
ecmascript:iteration [2025/09/08 14:05] – 作成 nullpon | ecmascript:iteration [2025/09/08 15:46] (現在) – nullpon | ||
---|---|---|---|
行 7: | 行 7: | ||
`[Symbol.iterator]`メソッドを実装していること。`[Symbol.iterator]`メソッドはイテレータプロトコルを実装したオブジェクトを返さなければならない。 | `[Symbol.iterator]`メソッドを実装していること。`[Symbol.iterator]`メソッドはイテレータプロトコルを実装したオブジェクトを返さなければならない。 | ||
+ | |||
+ | |||
+ | Array、NodeList、Set、Mapなどは反復可能プロトコルを実装している。 | ||
+ | |||
## イテレータプロトコル | ## イテレータプロトコル | ||
行 44: | 行 48: | ||
console.log(num); | console.log(num); | ||
} | } | ||
- | |||
console.log(Array.from(iterable)); | console.log(Array.from(iterable)); | ||
``` | ``` | ||
+ | |||
+ | 同じオブジェクトで反復可能プロトコル、イテレータプロトコル両方を実装しても構わない | ||
+ | |||
+ | ```javascript | ||
+ | const iteration = { | ||
+ | count: 0, | ||
+ | next() { | ||
+ | if (this.count < 5) { | ||
+ | return { value: this.count++, | ||
+ | } | ||
+ | return { value: undefined, done: true }; | ||
+ | }, | ||
+ | [Symbol.iterator]() { | ||
+ | return this; | ||
+ | }, | ||
+ | }; | ||
+ | |||
+ | |||
+ | for (const num of iteration) { | ||
+ | console.log(num); | ||
+ | } | ||
+ | |||
+ | </ |
ecmascript/iteration.1757340314.txt.gz · 最終更新: by nullpon