# 十六.迭代器模式

  • 顺序访问一个集合
  • 使用者无需知道集合的内部数据结构

# 1.类图

# 2.代码

function createIterator(arr) {
    let index=0;
    return {
        next() {
            return index<arr.length?
                {value: arr[index++],done: false}:
                {done:true}
        }
    }
}
let it=createIterator([1,2]);
console.log(it.next());
console.log(it.next());
console.log(it.next());
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 3.场景

Array.prototype[Symbol.iterator] = function() {
  let index = 0
  return {
    next: () => {
      return index < this.length
        ? { value: this[index++], done: false }
        : { done: true }
    },
  }
}
let arr = [1, 2]
let it2 = arr[Symbol.iterator]()
console.log(it2.next())
console.log(it2.next())
console.log(it2.next())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let arr = [1, 2]
let [x, y] = arr
let arr2 = [1, ...arr]
console.log(arr2)
1
2
3
4
let generator = function*() {
  yield 1
  yield* [2, 3, 4]
  yield 5
}
var iterator = generator()
console.log(iterator.next())
console.log(iterator.next())
console.log(iterator.next())
console.log(iterator.next())
console.log(iterator.next())
console.log(iterator.next())
1
2
3
4
5
6
7
8
9
10
11
12