JS迭代器(3)

87 阅读1分钟

如何实现自定义类的迭代?

Array、Set、String、Map等类创建出来的对象都是可迭代对象: 在面向对象开发中,我们可以通过class定义一个自己的类,这个类可以创建很多的对象:
如果我们也希望自己的类创建出来的对象默认是可迭代的,那么在设计类的时候我们就可以添加上 @@iterator 方法;
话不多说,上代码:

class Classroom {
  constructor(address, name, students) {
    this.address = address
    this.name = name
    this.students = students
  }

  entry(newStudent) {
    this.students.push(newStudent)
  }

  [Symbol.iterator]() {
    let index = 0
    return {
      next: () => {
        if (index < this.students.length) {
          return { done: false, value: this.students[index++] }
        } else {
          return { done: true, value: undefined }
        }
      },
      return: () => {
        console.log("迭代器提前终止了~")
        return { done: true, value: undefined }
      }
    }
  }
}

const classroom = new Classroom("3幢5楼205", "计算机教室", ["james", "kobe", "curry", "why"])
classroom.entry("lilei")

for (const stu of classroom) {
  console.log(stu)
  if (stu === "why") break
}

迭代器的中断

迭代器在某些情况下会在没有完全迭代的情况下中断: 比如遍历的过程中通过break、continue、return、throw中断了循环操作;
比如在解构的时候,没有解构所有的值;

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

 return: () => {
        console.log("迭代器提前终止了~")
        return { done: true, value: undefined }
      }