iterator迭代器

114 阅读1分钟

for...in和for...of有什么区别

  • 遍历对象: for of 不可以,for in 可以
  • 遍历Map Set: for of 可以,for in 不可以
  • 遍历generator: for of 可以,for in 不可以

for in 用于可枚举数据 如对象、数组、字符串,得到key

for of 用于可迭代数据,Array、set容器、map容器、String、函数的arguments对象、NodeList(html元素节点列表)对象、TypeArray,得到value

iterator迭代器

迭代器(Iterator)是一种为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署 Iterator 接口,就可以完成遍历操作(即依次处理该数据结构的所有成员)。

Iterator 的作用有三个:一是为各种数据结构,提供一个统一的、简便的访问接口;二是使得数据结构的成员能够按某种次序排列;三是 ES6 创造了一种新的遍历命令for...of循环,Iterator 接口主要供for...of消费。

工作原理

  • 创建一个指针对象
  • 第一次调用对象的next方法,指针自动指向数据结构的第一个成员
  • 接下来不断调用next方法,指针一直往后移动,直到指向最后一个成员
  • 每调用next方法返回一个包含value和done属性的对象
  • 作用:自定义遍历数据

自定义遍历数据的例子:

let obj = {
  name: "L",
  stus: ["wudongqiankun", "zhuxian", "tunshixingkong", "luofeng"],
  [Symbol.iterator]: function () {
    let index = 0;
    return {
      next: () => {
         returnindex< this.stus.length
        ? { value: this.stus[index], done: false }
        : { value: undefined, done: true }
      },
    }
  },
}
for (let key of obj) {
  console.log(key);
}

让 for ... of能遍历对象

Object.prototype[Symbol.iterator] = function () {
  const keys = Reflect.ownKeys(this);
  let pointer = 0;
  // 返回遍历器对象
  return {
    next: () => {
       return pointer < keys.length
        ? { value: this[keys[pointer++]], done: false }
        : { value: undefined, done: true };
    },
  };
};