Skip to content

自定义迭代器

实现迭代器接口

任何实现了 Iterator 接口的对象都可以作为迭代器使用。

ts
class Counter {
  constructor(private limit: number) {}

  [Symbol.iterator]() {
    let count = 1,
      limit = this.limit;
    return {
      next() {
        if (count <= limit) {
          return { value: count++, done: false };
        } else {
          return { value: undefined, done: true };
        }
      },
    };
  }
}

const counter = new Counter(3);
for (const num of counter) {
  console.log(num); // 1 2 3
}

提前终止迭代

可选的 return() 方法定义了在迭代器被提前关闭时执行的操作。

ts
class Counter2 {
  constructor(private limit: number) {}

  [Symbol.iterator]() {
    let count = 1,
      limit = this.limit;
    return {
      next() {
        if (count <= limit) {
          return { value: count++, done: false };
        } else {
          return { value: undefined, done: true };
        }
      },
      return() {
        console.log("Terminating early");
        return { value: undefined, done: true };
      },
    };
  }
}

const counter2 = new Counter2(3);
for (const num of counter2) {
  if (num && num > 2) {
    break;
  }
  console.log(num);
}
// 1
// 2
// Terminating early