迭代器(Iterator)和生成器(Generation)

一、用生成器给对象定义迭代器

常规方法

const obj = {
  a: 1,
  b: 2,
  c: 3,
  [Symbol.iterator]() {
    let [index, values] = [0, Object.values(this)]
    return {
      next() {
        const done = (index >= values.length)
        const value = done ? undefined : values[index++]
        return {
          done,
          value
        }
      }
    }
  }
}
for (let v of obj) {
  console.log(v) // 1 2 3
}

"迭代器(Iterator)和生成器(Generation)"继续阅读