ES6对迭代器的实现

理解并手写实现ES6迭代器协议,包括可迭代对象和迭代器对象的创建

问题

迭代器(Iterator)是ES6引入的一种遍历机制,它提供了一种统一的接口来访问不同的数据结构。本题要求手写实现ES6的迭代器协议,理解可迭代对象(Iterable)和迭代器对象(Iterator)的工作原理。

解答

// 1. 基础迭代器实现
function createIterator(array) {
  let index = 0;
  
  return {
    next() {
      if (index < array.length) {
        return {
          value: array[index++],
          done: false
        };
      } else {
        return {
          value: undefined,
          done: true
        };
      }
    }
  };
}

// 2. 可迭代对象实现(实现 Symbol.iterator 方法)
class MyIterable {
  constructor(data) {
    this.data = data;
  }
  
  // 实现可迭代协议
  [Symbol.iterator]() {
    let index = 0;
    const data = this.data;
    
    // 返回迭代器对象
    return {
      next() {
        if (index < data.length) {
          return {
            value: data[index++],
            done: false
          };
        }
        return {
          value: undefined,
          done: true
        };
      }
    };
  }
}

// 3. 自定义范围迭代器
class RangeIterator {
  constructor(start, end, step = 1) {
    this.start = start;
    this.end = end;
    this.step = step;
  }
  
  [Symbol.iterator]() {
    let current = this.start;
    const end = this.end;
    const step = this.step;
    
    return {
      next() {
        if (current < end) {
          const value = current;
          current += step;
          return { value, done: false };
        }
        return { value: undefined, done: true };
      }
    };
  }
}

// 4. 对象属性迭代器
class ObjectIterator {
  constructor(obj) {
    this.obj = obj;
    this.keys = Object.keys(obj);
  }
  
  [Symbol.iterator]() {
    let index = 0;
    const keys = this.keys;
    const obj = this.obj;
    
    return {
      next() {
        if (index < keys.length) {
          const key = keys[index++];
          return {
            value: { key, value: obj[key] },
            done: false
          };
        }
        return { value: undefined, done: true };
      }
    };
  }
}

// 5. 无限迭代器(斐波那契数列)
class FibonacciIterator {
  [Symbol.iterator]() {
    let prev = 0;
    let curr = 1;
    
    return {
      next() {
        const value = curr;
        [prev, curr] = [curr, prev + curr];
        return { value, done: false };
      }
    };
  }
}

使用示例

// 示例1: 基础迭代器
const iterator = createIterator([1, 2, 3]);
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: undefined, done: true }

// 示例2: 可迭代对象(支持 for...of)
const myIterable = new MyIterable(['a', 'b', 'c']);
for (const item of myIterable) {
  console.log(item); // 'a', 'b', 'c'
}

// 使用扩展运算符
console.log([...myIterable]); // ['a', 'b', 'c']

// 示例3: 范围迭代器
const range = new RangeIterator(0, 10, 2);
console.log([...range]); // [0, 2, 4, 6, 8]

for (const num of new RangeIterator(1, 5)) {
  console.log(num); // 1, 2, 3, 4
}

// 示例4: 对象属性迭代器
const obj = { name: 'Alice', age: 25, city: 'Beijing' };
const objIterator = new ObjectIterator(obj);

for (const item of objIterator) {
  console.log(`${item.key}: ${item.value}`);
}
// 输出:
// name: Alice
// age: 25
// city: Beijing

// 示例5: 无限迭代器(需要手动控制)
const fib = new FibonacciIterator();
const fibIterator = fib[Symbol.iterator]();

// 获取前10个斐波那契数
const first10Fib = [];
for (let i = 0; i < 10; i++) {
  first10Fib.push(fibIterator.next().value);
}
console.log(first10Fib); // [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

关键点

  • 迭代器协议:对象必须实现 next() 方法,返回包含 valuedone 属性的对象
  • 可迭代协议:对象必须实现 [Symbol.iterator]() 方法,返回一个迭代器对象
  • done 标志done: false 表示还有值可迭代,done: true 表示迭代结束
  • value 属性:当 donefalse 时,value 包含当前迭代的值;当 donetrue 时,value 通常为 undefined
  • for…of 循环:只能用于实现了可迭代协议的对象
  • 内置可迭代对象:Array、String、Map、Set、arguments 等都实现了迭代器协议
  • 扩展运算符... 运算符内部调用了迭代器接口
  • 状态管理:迭代器需要维护当前遍历的位置状态
  • 惰性求值:迭代器按需生成值,适合处理大数据集或无限序列