symbol,iterator,generator (二)

Iterator :

 返回的结果是:{value, done}

 

 

写一个基于class的Iterator:


class MyIterator {
 
constructor(arr) {
   this.arr = arr
   this.i = 0;
}

next() {

    let done = (this.i >= this.arr.length)
    let value = !done ? this.arr[this.i++] : undefined

    return {
        value,
        done }
     
     }
}

var iterator = new MyIterator([1, 2, 3]);

console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());

 

posted @ 2018-06-24 23:37  hh9515  阅读(114)  评论(0编辑  收藏  举报