ES6系列之迭代器和生成器

82 阅读7分钟

迭代器

迭代器(iterator),使用户在容器对象(container,例如链表或数组)上遍访的对象,使用该接口无需关心对象的内部实现细节

  • 其行为像数据库中的光标,迭代器最早出现在 1974 年设计的 CLU 编程语言中;
  • 在各种编程语言的实现中,迭代器的实现方式各不相同,但是基本都有迭代器,比如 Java、Python

从迭代器的定义我们可以看出来,迭代器是帮助我们对某个数据结构进行遍历的对象

在 JavaScript 中,迭代器也是一个具体的对象,这个对象需要符合迭代器协议(iterator protocol):

  • 迭代器协议定义了产生一系列值(无论是有限还是无限个)的标准方式
  • 在 JavaScript 中这个标准就是一个特定的 next 方法

next 方法有如下的要求:

  • 一个无参数或者一个参数的函数,返回一个应当拥有以下两个属性的对象
  • done(boolean)
    • 如果迭代器可以产生序列中的下一个值,则为 false。(这等价于没有指定 done 这个属性。)
    • 如果迭代器已将序列迭代完毕,则为 true。这种情况下,value 是可选的,如果它依然存在,即为迭代结束之后的默认返回值
  • value
    • 迭代器返回的任何 JavaScript 值。done 为 true 时可省略

概念比较抽象,我们用代码来诠释:

const res = [1, 2, 3, 4, 5]

// 给res创建一个迭代器
let index = 0
const resIterator = {
  // 迭代器需要实现一个next方法
  // next返回一个对象(存在done和value属性)
  next: () => {
    // 对res中的元素进行遍历
    return index < res.length
      ? { done: false, value: res[index++] }
      : { done: true, value: undefined }
  },
}

console.log(resIterator.next()) // { done: false, value: 1 }
console.log(resIterator.next()) // { done: false, value: 2 }
console.log(resIterator.next()) // { done: false, value: 3 }
console.log(resIterator.next()) // { done: false, value: 4 }
console.log(resIterator.next()) // { done: false, value: 5 }
console.log(resIterator.next()) // { done: false, value: undefined }

如果我们还有数组需要迭代器,是不是又得重复上面的操作,这样显然不好,所以我们可以封装一个函数

const res = [1, 2, 3, 4, 5]

function createArrayIterator(arr) {
  if (arr instanceof Array) {
    let index = 0
    return {
      next: () => {
        return index < arr.length
          ? { done: false, value: arr[index++] }
          : { done: true, value: undefined }
      },
    }
  }
  throw new Error('请传入一个数组')
}

const arrIterator = createArrayIterator(res)
console.log(arrIterator.next()) // {done: false, value: 1}
console.log(arrIterator.next()) // {done: false, value: 2}
console.log(arrIterator.next()) // {done: false, value: 3}
console.log(arrIterator.next()) // {done: false, value: 4}
console.log(arrIterator.next()) // {done: false, value: 5}
console.log(arrIterator.next()) // {done: false, value: undefined}

但是上面的代码整体来说看起来是有点复杂的

  • 事实上我们可以对上面的代码进行进一步的封装,让其变成一个可迭代对象

可迭代对象

什么又是可迭代对象呢?

  • 它和迭代器是不同的概念
  • 当一个对象实现了 迭代器 协议时,它就是一个可迭代对象
  • 这个对象的要求是必须实现 @@iterator 方法,在 JS 代码中我们使用 Symbol.iterator

当然我们要问一个问题,我们转成这样的一个东西有什么好处呢?

  • 当一个对象变成一个可迭代对象的时候,就可以进行某些迭代操作
  • 比如 for...of 操作时,其实就会调用它内部的 @@iterator 方法
const info = {
  names: ['zs', 'ls', 'ww', 'zl'],
  // 使用计算属性名实现一个约定的Symbol.iterator函数
  [Symbol.iterator]: function () {
    let index = 0
    return {
      // 箭头函数改变this指向
      next: () => {
        return index < this.names.length
          ? { done: false, value: this.names[index++] }
          : { done: true, value: undefined }
      },
    }
  },
}

// 这样我们的info就是一个可迭代对象了
// 我们知道默认对象是不能使用for...of来遍历的
// 因为for...of只能遍历可迭代对象
// info现在变成了一个可迭代对象
// 所有我们通过这样的方法就可以实现for...of遍历对象了

for (const item of info) {
  console.log(item) // zs ls ww zl
}

我们可能会想这感觉没什么用啊!

  • 就用一个 for...of 还要写一个 Symbol.iterator 函数

原生迭代器对象

事实上我们平时创建的很多原生对象已经实现了可迭代协议,会生成一个迭代器对象的:

  • String、Array、Map、Set、arguments 对象、NodeList 集合
const name = 'tao'
for (const item of name) {
  console.log(item)
}

const names = ['zs', 'ls', 'ww', 'zl']
for (const item of names) {
  console.log(item)
}

function foo() {
  for (const item of arguments) {
    console.log(item)
  }
}

foo(1, 2, 3)

可迭代对象的应用

那么这些东西可以被用在哪里呢?

  • JavaScript 中语法:for ...of、展开语法(spread syntax)、yield*、解构赋值(Destructuring_assignment)
  • 创建一些对象时:new Map([Iterable])、new WeakMap([iterable])、new Set([iterable])、new WeakSet([iterable])
  • 一些方法的调用:Promise.all(iterable)、Promise.race(iterable)、Array.from(iterable)

for...of 刚刚用了,这里说一下展开语法

  • 如果没有学过生成器的话,我们都知道对象在 ES9 前是不能使用展开语法的
  • 因为展开语法接收一个可迭代对象为参数
  • ES9 以后对象使用展开语法的时候不是可迭代对象的应用,而是内部对象做了其它的特殊处理
  • 不过我们还是可以举一个特别的例子的
const info = {}

// 肯定报错
console.log(...info)

如果是一个可迭代对象就可以

const info = {
  names: ['zs', 'ls', 'ww', 'zl'],
  [Symbol.iterator]() {
    let index = 0
    return {
      next: () => {
        return index < this.names.length
          ? { done: false, value: this.names[index++] }
          : { done: true, value: undefined }
      },
    }
  },
}

console.log(...info) // zs ls ww zl

还有比如我们自学看视频的话都讲 Array.from 传入一个类数组对象(比如:argument),然后就可以转成数组了

  • 不过你有没有想过为什么
  • 其实 mdn 有了详细的讲解
  • Array.from 要求传入一个类数组或者是一个可迭代对象
  • 这就解释了为什么以前我们学习的时候视频都说 argument 是一个类数组对象(其实更明确的说它是一个可迭代对象,当然它也是一个类数组对象)
  • 只不过如果没有学过的话,肯定不知道可迭代对象是什么
function foo() {
  const arr = Array.from(arguments)
  console.log(arr) // [ 1, 2, 3 ]
}

foo(1, 2, 3)

自定义类的迭代

如果我们也希望自己的类创建出来的对象默认是可迭代的,那么在设计类的时候我们就可以添加上 @@iterator 方法

class Person {
  constructor(name, age, height, friends) {
    this.name = name
    this.age = age
    this.height = height
    this.friends = friends
  }

  // 我们想要遍历friends就可以实现一个迭代器
  [Symbol.iterator]() {
    let index = 0
    return {
      next: () => {
        return index < this.friends.length
          ? { done: false, value: this.friends[index++] }
          : { done: true, value: undefined }
      },
    }
  }
}

const p1 = new Person('tao', 18, 1.88, ['zs', 'ls', 'ww', 'zl'])
const p2 = new Person('sandy', 21, 1.65, ['tao'])

for (const item of p1) {
  console.log(item) // zs ls ww zl
}

不过我们可能很少会这样用,如果有特殊的需求可以这样

迭代器的中断

迭代器在某些情况下会在没有完全迭代的情况下中断:

  • 比如遍历的过程中通过 breakreturnthrow 中断了循环操作
  • 比如在解构的时候,没有解构所有的值

那么这个时候我们想要监听中断的话,可以添加 return 方法:

class Person {
  constructor(name, age, height, friends) {
    this.name = name
    this.age = age
    this.height = height
    this.friends = friends
  }

  [Symbol.iterator]() {
    let index = 0
    return {
      next: () => {
        return index < this.friends.length
          ? { done: false, value: this.friends[index++] }
          : { done: true, value: undefined }
      },
      return: () => {
        console.log('迭代器终止了')
        // 因为迭代器中需要返回{done,value}这样的解构,因为迭代器终止了
        // 所以我们就直接返回{ done: true, value: undefined }
        return { done: true, value: undefined }
      },
    }
  }
}

const p1 = new Person('tao', 18, 1.88, ['zs', 'ls', 'ww', 'zl'])
const p2 = new Person('sandy', 21, 1.65, ['tao'])

for (const item of p1) {
  if (item === 'ww') {
    break
  }
}

什么是生成器?

生成器是 ES6 中新增的一种函数控制、使用的方案,它可以让我们更加灵活的控制函数什么时候继续执行、暂停执行

  • 平时我们会编写很多的函数,这些函数终止的条件通常是返回值或者发生了异常

生成器函数也是一个函数,但是和普通的函数有一些区别:

  • 首先,生成器函数需要在 function 的后面加一个符号:*
  • 其次,生成器函数可以通过 yield 关键字来控制函数的执行流程:
  • 最后,生成器函数的返回值是一个 Generator(生成器):
    • 生成器事实上是一种特殊的迭代器

生成器函数基本使用

默认调用生成器函数,函数体内的代码是不会执行的

  • 生成器函数会返回一个生成器对象
  • 之后通过调用生成器对象里的 next 方法执行函数体内的代码
function* foo() {
  console.log('111')
  console.log('222')
  console.log('333')
  console.log('444')
  console.log('555')
  console.log('666')
}

const fooGenerator = foo()
fooGenerator.next()

/**
 * 111
 * 222
 * 333
 * 444
 * 555
 * 666
 */

yield 关键字

yield 用于控制函数的执行流程

  • 默认调用生成器对象的 next 方法,函数内部的代码就会依次执行
  • yield 表示暂停的意思,当函数执行的时候遇到 yield,函数就会停止执行
  • 之后想继续执行函数的话,需要再次调用 next 方法
function* foo() {
  console.log('111')
  console.log('222')
  yield
  console.log('333')
  console.log('444')
  yield
  console.log('555')
  console.log('666')
}

const fooGenerator = foo()
fooGenerator.next() // 111 222
fooGenerator.next() // 333 444
fooGenerator.next() // 555 666

如果 yield 后面有值,那么后面的值会作为当前 next 方法的返回值

function* foo() {
  console.log('111')
  console.log('222')
  yield '第一次yield'
  console.log('333')
  console.log('444')
  yield '第二次yield'
  console.log('555')
  console.log('666')
  yield '第三次yield'
}

const fooGenerator = foo()
console.log(fooGenerator.next()) // { value: '第一次yield', done: false
console.log(fooGenerator.next()) // { value: '第二次yield', done: false
console.log(fooGenerator.next()) // { value: '第三次yield', done: false }
console.log(fooGenerator.next()) // { value: undefined, done: true }

生成器传递参数 – next 函数

既然是一个函数,那么函数肯定是可以传递参数的

  • 我们在调用 next 函数的时候,可以给 next 传递参数,那么这个参数会作为上一个 yield 语句的返回值
function* foo(name) {
  // 我们如何在这里拿到参数喃,这里没有yield
  // 好好想一想,我们是不是可以在foo()这里获取参数
  // 所以第一次next是不传递参数的
  // 想在生成器函数第一个yield前面获取参数就可以直接在生成器函数的形参里获取
  console.log('111', name) // 111 name
  console.log('222', name) // 222 name
  const name2 = yield '第一次yield'
  console.log('333', name2) // 333 name2
  console.log('444', name2) // 444 name2
  const name3 = yield '第二次yield'
  console.log('555', name3) // 555 name3
  console.log('666', name3) // 666 name3
  yield '第三次yield'
}

const fooGenerator = foo('name')
console.log(fooGenerator.next()) // { value: '第一次yield', done: false
console.log(fooGenerator.next('name2')) // { value: '第二次yield', done: false
console.log(fooGenerator.next('name3')) // { value: '第三次yield', done: false }
console.log(fooGenerator.next()) // { value: undefined, done: true }

生成器提前结束 – return 函数

还有一个可以给生成器函数传递参数的方法是通过 return 函数:

  • return 之后整个生成器函数就会停止迭代了
  • return 里的参数会作为当前函数返回值的 value 值
function* foo() {
  console.log('111') // 111 name
  console.log('222') // 222 name
  const name2 = yield '第一次yield'
  console.log('333', name2) // 333 name2
  console.log('444', name2) // 444 name2
  const name3 = yield '第二次yield'
  console.log('555', name3) // 555 name3
  console.log('666', name3) // 666 name3
  yield '第三次yield'
}

const fooGenerator = foo()
console.log(fooGenerator.next()) // {value: '第一次yield', done: false}
console.log(fooGenerator.return('name2')) // {value: 'name2', done: true}
console.log(fooGenerator.next('name3')) // {value: undefined, done: true}
console.log(fooGenerator.next()) // {value: undefined, done: true}

生成器抛出异常 – throw 函数

除了给生成器函数内部传递参数之外,也可以给生成器函数内部抛出异常:

  • 抛出异常后我们可以在生成器函数中捕获异常
  • 但是在 catch 语句中不能继续 yield 新的值了,但是可以在 catch 语句外使用 yield 继续中断函数的执行
function* foo() {
  console.log('函数开始执行') // 函数开始执行

  try {
    yield 111
  } catch (error) {
    console.log('内部捕获异常:', error) // 内部捕获异常: 抛出一个异常
  }

  yield 222

  console.log('函数执行完毕') // 函数执行完毕
}

const fooGenerator = foo()

console.log(fooGenerator.next()) // {value: 111, done: false}
console.log(fooGenerator.throw('抛出一个异常')) //  {value: 222, done: false}
console.log(fooGenerator.next()) //  {value: undefined, done: true}

生成器替代迭代器

因为生成器也是迭代器,所以我们可以使用生成器来替代迭代器

const names = ['zs', 'ls', 'ww', 'zl']

function* createArrayGenerator(arr) {
  if (arr instanceof Array) {
    yield arr[0]
    yield arr[1]
    yield arr[2]
    yield arr[3]
  }
}

const arrGenerator = createArrayGenerator(names)
console.log(arrGenerator.next()) // { value: 'zs', done: false }
console.log(arrGenerator.next()) // { value: 'ls', done: false }
console.log(arrGenerator.next()) // { value: 'ww', done: false }
console.log(arrGenerator.next()) // { value: 'zl', done: false }
console.log(arrGenerator.next()) // { value: undefined, done: true }

我们发现 yield 是有规律的,我们是不是可以使用 for 循环

const names = ['zs', 'ls', 'ww', 'zl']

function* createArrayGenerator(arr) {
  if (arr instanceof Array) {
    for (let i = 0; i < arr.length; i++) {
      yield arr[i]
    }
  }
}

const arrGenerator = createArrayGenerator(names)
console.log(arrGenerator.next()) // { value: 'zs', done: false }
console.log(arrGenerator.next()) // { value: 'ls', done: false }
console.log(arrGenerator.next()) // { value: 'ww', done: false }
console.log(arrGenerator.next()) // { value: 'zl', done: false }
console.log(arrGenerator.next()) // { value: undefined, done: true }

事实上我们还可以使用 yield*来生产一个可迭代对象:

  • 即表示 yield* 后面跟上一个可迭代对象
  • 这个时候相当于是一种 yield 的语法糖,只不过会依次迭代这个可迭代对象,每次迭代其中的一个值
const names = ['zs', 'ls', 'ww', 'zl']

function* createArrayGenerator(arr) {
  // 数组是一个可迭代对象
  yield* arr
}

const arrGenerator = createArrayGenerator(names)
console.log(arrGenerator.next()) // { value: 'zs', done: false }
console.log(arrGenerator.next()) // { value: 'ls', done: false }
console.log(arrGenerator.next()) // { value: 'ww', done: false }
console.log(arrGenerator.next()) // { value: 'zl', done: false }
console.log(arrGenerator.next()) // { value: undefined, done: true }

自定义类迭代 – 生成器实现

在之前的自定义类迭代中,我们也可以换成生成器:

class Person {
  constructor(name, age, height, friends) {
    this.name = name
    this.age = age
    this.height = height
    this.friends = friends
  }

  // 看这样的代码是不是就很优雅
  *[Symbol.iterator]() {
    yield* this.friends
  }
}

const p1 = new Person('tao', 18, '1.88', ['zs', 'ls', 'ww', 'zl'])

for (const item of p1) {
  console.log(item) // zs ls ww zl
}