实现一个迭代器Iterator

# 实现一个迭代器Iterator

  • 现在js有四种数据集合 1.array 2.object 3.set 4.map、
  • 所以需要统一的接口机制,处理不同的数据结构,任何数据结构只要部署iterator就可以完成遍历操作
  • 作用:
  • 1.为所有的数据结构提供一个统一的、简便的访问接口
  • 2.使得数据结构的成员可以按照某种特定的次序排列
  • 3.创造了for...of...
  • 遍历过程:
  • 1.创建一个指针对象,指向数据结构的起始位置
  • 2.调用指针对象的next,可以指向数据结构下一个成员,直到数据结构结束位置
  • 3.每一次调用next 都会返回value和done两个属性的对象,其中value是属性当前的值,done是布尔值表示遍历是否结束
//函数实现
function myIterator(array) {
  let i = 0;
  return {
    next: function () {
      return {
        value: array[i++],
        done: i >= array.length ? false : true,
      };
    },
  };
}
1
2
3
4
5
6
7
8
9
10
11
12
class MyIterator {
  constructor(params) {
    this.index = 0;
    this.value = params;
  }
  [Symbol.iterator]() {
    return this;
  }
  next() {
    return {
      value: this.value[this.index++],
      done: this.index > this.value.length ? true : false,
    };
  }
}

var it = new MyIterator(["a", "b", "c"]);
console.log(it.next()); // {value: "a", done: false}
console.log(it.next()); // {value: "b", done: false}
console.log(it.next()); // {value: "c", done: false}
console.log(it.next()); // "{ value: undefined, done: true }"
console.log(it.next()); // "{ value: undefined, done: true }"
console.log(it.next()); // "{ value: undefined, done: true }"



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//原生实现
// 部署了遍历器接口。调用这个接口,就会返回一个遍历器对象。
let strIteratorObj = ["y", "b", "z"][Symbol.iterator](); //得到迭代器
console.log(strIteratorObj.next());
console.log(strIteratorObj.next());
console.log(strIteratorObj.next());
console.log(strIteratorObj.next());


1
2
3
4
5
6
7
8
9
上次更新: 2022/7/28 下午9:01:35