一、迭代器介绍

迭代器(iterator)是一种接口,为各种不同的数据结构提供对立的拜访机制。任何数据结构只有部署iterator接口,就能够实现遍历操作。

  1. ES6发明了一种新的遍历命令for...of循环,iterator接口次要供for...of应用
  2. 原生具备iterator接口的数据(可用for of遍历)

    • Array
    • Arrguments
    • Set
    • Map
    • String
    • TypedArray
    • NodeList
  3. 原理
    (1) 创立一个指针对象,指向以后数据结构的起始地位
    (2) 第一次调用对象的next办法,指针主动指向数据结构的第一个成员
    (3) 接下来一直调用next办法,指针始终往后挪动,直到指向最初一个成员
    (4) 每调用next办法返回一个蕴含valuedone属性的对象

二、简略实现

const rng = ['letme', 'mlxg', 'xiaohu', 'uzi', 'ming'];let iterator = rng[Symbol.iterator]();console.log(iterator.next());console.log(iterator.next());console.log(iterator.next());console.log(iterator.next());console.log(iterator.next());console.log(iterator.next());

三、实例

// 申明一个对象const newRng = {    name: "皇族",    member: [        'letme',        'mlxg',        'uzi',        'ming',    ],    [Symbol.iterator]() {        let index = 0        let that = this;        return {            next: function () {                if (index < that.member.length) {                    const result = {                        value: that.member[index],                        done: false                    }                    index++;                    return result                } else {                    return {                        value: undefined,                        done: true                    }                }            }        }    }}// 遍历此对象for (let v of newRng) {    console.log(v);}// 后果// letme// mlxg// uzi// ming