0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

初心者による ES6 イテレーター

0
Posted at

概要

イテレーターとは、オブジェクトの内容を列挙するための仕組みを備えたオブジェクトです。Array, String, Map, Setなどの組み込みオブジェクトは、デフォルトでイテレーターが備わっているため、for...ofで要素を列挙できる。これはC言語にもあるので確認してみる。

C++ iterator

C++でのiteratorを復習してみる。C++ではiteratorは「共通のインターフェイスでコンテナに対する反復処理を行うことができるポインタのようなもの」と考えることができる。

main.cpp
# include<iostream>
# include<vector>
using namespace std

int main() {
 vector<int> V;
 vector<int>::iterator i;

 V.assign(5, 5)
 for(i = V.begin(); i != V.end(); i++){
 cout << *i << endl;
 }
}

V(ベクトルコンテナ)に格納されている要素を列挙している。
これと同じことをjavascriptで表してみる。

javascript iterator

sample.js
let data_ary['1', '2', '3']
let itr = data_ary[Symbol.iterator]()
let d
while(d = itr.next()){
 if(d.done) { break }
 console.log(d.done)
 console.log(d.value)
}

[Symbol.itrator]メソッドは、配列内の要素を列挙するためのイテレーター(iteratorオブジェクト)を返します。イテレーターは配列の次の要素を取り出すためのnextメソッドを持ちます。それぞれの値は、

done : イテレーターが終端に到達したか(=次の要素がないか)
value : 次の要素の値

列挙することが可能な自作classを作った場合の扱い方は、

sample.js
class Data {
 constructor(data){
  this.data = data
 }
 
 [Symbol.iterator](){
  let current = 0
  let that = this
  return {
   next(){
    //オブジェクトを返す
    return current < that.data.length ? 
     {value: that.data[current++], done: false} : 
     {done: true}
   }
  }
 }
}
let iterator = new Data(['1', '2', '3'])
for(let value of iterator){
 console.log(value)
}

for...of命令は、内部的に「イテレーターの取得からdoneメソッドによる判定、valueプロパティによる値の取り出しまで」をすべてしてくれているのである。よって、Symbol.iteratorを組み込んでおくことでfor...ofで中身を列挙できる。

参考資料

山田祥寛様 「Javascript 本格入門」

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?