在JavaScript中,迭代器是一种允许我们遍历集合中元素的对象。迭代器对象具有一个next()方法,该方法返回valuedonevalue是当前迭代的值,done属性是一个布尔值,表示是否到达了集合的末尾。

迭代器协议

一个迭代器对象必须具备以下特性:

  1. next()方法:每次调用返回一个对象,其结构为{value:...,done:...}。如果迭代完成,value可能是任意值,done则为true
  2. 可选的return()方法:允许提前终止迭代,其可选地返回一个值。
  3. 可选的throw()方法:允许在迭代过程中抛出错误。

创建迭代器

使用Symbol.iterator来实现迭代器。

const myArray = ['a', 'b', 'c']
const myIterator = {
    data: myArray,
    index: 0,

    [Symbol.iterator] () {
        return this
    },

    next () {
        if (this.index < this.data.length) {
            return { value: this.data[this.index++], done: false }
        } else {
            return { done: true }
        }
    }
}

for (let item of myIterator) {
    console.log('🚀 ~ item:', item)
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

生成器函数

生成器函数是实现迭代器的一种更简便的方式。生成器函数使用function*语法定义,并且可以使用yield关键字来产生一系列值。当生成器函数被调用时,它返回一个迭代器对象,该对象可以使用next()方法来迭代。

function* numberGenerator(max) {
  for (let i = 0; i < max; i++) {
    yield i
  }
}

const gen = numberGenerator(5)

console.log(gen.next()) // { value: 0, done: false }
console.log(gen.next()) // { value: 1, done: false }
console.log(gen.next()) // { value: 2, done: false }
console.log(gen.next()) // { value: 3, done: false }
console.log(gen.next()) // { value: 4, done: false }
console.log(gen.next()) // { value: undefined, done: true }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.