可迭代对象是数组的泛化,是定义了内置迭代器方法 Symbol.iterator 的对象。是可以在for..of 循环中使用的对象。
为了让对象可以迭代,我们需要给对象添加一个迭代器--Symbol.iterator。
迭代器是一个包含next()方法的对象,next()是一个需要自定义的方法,用于定义每次调用时应返回的值和是否完成迭代的条件。
例如:
-
-
- let range = {
- a: 1,
- b: 5,
- };
- // 1. for..of 调用首先会调用这个:
- range[Symbol.iterator] = function () {
- // 返回迭代器对象(iterator object):
- // 2. 接着定义next() 方法
- return {
- current: this.a,
- last: this.b,
- // 3. next() 在 for..of 的每一轮循环迭代中被调用
- next() {
- // 4. 它将会返回 {done:.., value :...} 格式的对象
- if (this.current <= this.last) {
- return { done: false, value: this.current++ };
- } else {
- return { done: true };
- }
- },
- };
- };
-
- // 现在它可以运行了!
- for (let num of range) {
- console.log(num); // 1 2 3 4 5
- }
-
也可以将对象自身作为迭代器,例如:
-
- let range = {
- a: 1,
- b: 5,
-
- [Symbol.iterator]() {
- this.current = this.a;
- return this;
- },
-
- next() {
- if (this.current <= this.b) {
- return { done: false, value: this.current++ };
- } else {
- return { done: true };
- }
- },
- };
-
- for (let num of range) {
- console.log(num); // 1 2 3 4 5
- }
-
当一个对象可迭代,我们就可以使用扩展运算符(...)或者Array.from()进行遍历
例如:
-
- let range = {
- a: 1,
- b: 5,
- };
- range[Symbol.iterator] = function () {
- return {
- current: this.a,
- last: this.b,
- next() {
- if (this.current <= this.last) {
- return { done: false, value: this.current++ };
- } else {
- return { done: true };
- }
- },
- };
- };
-
- console.log(Array.from(range)); //[1, 2, 3, 4, 5]
- console.log([...range]); //[1, 2, 3, 4, 5]
-