MST

星途 面试题库

面试题:JavaScript中迭代器的基本实现

请用JavaScript实现一个简单的迭代器,用于遍历数组[1, 2, 3, 4, 5],并解释每一步的原理。
20.0万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
// 创建数组
const arr = [1, 2, 3, 4, 5];
// 创建迭代器对象
const iterator = {
    index: 0,
    next() {
        if (this.index < arr.length) {
            return {
                value: arr[this.index++],
                done: false
            };
        } else {
            return {
                value: undefined,
                done: true
            };
        }
    }
};
// 使用迭代器
let result = iterator.next();
while (!result.done) {
    console.log(result.value);
    result = iterator.next();
}

原理解释

  1. 创建数组:首先定义了要遍历的数组 arr,值为 [1, 2, 3, 4, 5]
  2. 创建迭代器对象
    • index属性:用于记录当前遍历到数组的位置,初始值为0。
    • next方法:每次调用next方法时:
      • 首先判断index是否小于数组的长度。如果小于,说明还没有遍历完数组,返回一个包含value(当前数组元素)和done(表示是否遍历结束,这里为false)的对象,并将index自增1。
      • 如果index大于或等于数组长度,说明数组已遍历完,返回一个valueundefineddonetrue的对象。
  3. 使用迭代器
    • 先调用一次iterator.next()获取第一个值,返回的结果保存在result中。
    • 使用while循环,只要result.donefalse,就说明还没遍历完,打印当前的result.value,然后再次调用iterator.next()获取下一个值并更新result,直到result.donetrue,此时数组遍历结束。