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());