js迭代器

发布于:2025-07-22 ⋅ 阅读:(9) ⋅ 点赞:(0)


前言

迭代器是 JSt 中一种特殊的对象,它提供了一种统一的、通用的方式遍历个各种不同类型的数据结构。

可以遍历的数据结构包括:数组、字符串、Set、Map 等可迭代对象。我们也可以自定义实现迭代器,以支持遍历自定义的数据结构。

实现原理:

迭代器的实现原理是通过定义一个特定的next() 方法,在每次迭代中返回一个包含两个属性的对象:donevalue
next()方法

  1. 参数:无参数或者有一个参数。
  2. 返回值:返回一个有两个属性的对象。属性值如下:
    done:布尔值,表示迭代是否完成
    value:当前步骤的值

每次调用next方法,都会改变value值至下一步,直到迭代完成

据此,可以给数组手写一个迭代器函数

const strArr = ['a', 'b', 'c', 'd'];

// 为数组封装迭代器
function create(arr) {
  let index = 0;
  return {
    next: () => {
      if (index < arr.length) {
        return { done: false, value: arr[index++] };
      } else {
        return { done: true };
      }
    },
  };
}

const str = create(strArr);
console.log(JSON.stringify(str.next()));
console.log(JSON.stringify(str.next()));
console.log(JSON.stringify(str.next()));
console.log(JSON.stringify(str.next()));
console.log(JSON.stringify(str.next()));
//输出
// {"done":false,"value":"a"}
// 测试.html:28 {"done":false,"value":"b"}
// 测试.html:29 {"done":false,"value":"c"}
// 测试.html:30 {"done":false,"value":"d"}
// 测试.html:31 {"done":true}

可以看到 ,每调用一次next,value会向后移动,直至遍历完毕

调用迭代器

语法

const a=可迭代对象[Symbol.iterator]()

实例如下

const myArr = ['a', 'b', 'c', 'd'];

// 获取数组自带的迭代器对象
const myIterator = myArr[Symbol.iterator]();

// 通过迭代器的 next() 方法遍历数组
console.log(JSON.stringify(myIterator.next()));
console.log(JSON.stringify(myIterator.next()));
console.log(JSON.stringify(myIterator.next()));
console.log(JSON.stringify(myIterator.next()));
console.log(JSON.stringify(myIterator.next()));
//输出
// {"value":"a","done":false}
// 测试.html:17 {"value":"b","done":false}
// 测试.html:18 {"value":"c","done":false}
// 测试.html:19 {"value":"d","done":false}
// 测试.html:20 {"done":true}

自制迭代器

很多数据对象由于不是可迭代对象,我们可以为其手动创建一个迭代器

与函数不同,这次将其封装在对象中,并且此后调用方法一致

const myObj1 = {
  strArr: ['a', 'b', 'c', 'd'],
  // 在 myObj1 的内部创建一个迭代器
  [Symbol.iterator]: function () {
    let index = 0;
    const Iterator = {
      next: function () {
        if (index < myObj1.strArr.length) {
          return { done: false, value: myObj1.strArr[index++] };
        } else {
          return { done: true };
        }
      },
    };
    return Iterator;
  },
};

// 获取 myObj1 的迭代器对象
const myIterator = myObj1[Symbol.iterator]();
// 通过迭代器遍历 myObj1.strArr 的数据
console.log(JSON.stringify(myIterator.next()));
console.log(JSON.stringify(myIterator.next()));
console.log(JSON.stringify(myIterator.next()));
console.log(JSON.stringify(myIterator.next()));
console.log(JSON.stringify(myIterator.next()));
// 输出
// {"done":false,"value":"a"}
// 测试.html:32 {"done":false,"value":"b"}
// 测试.html:33 {"done":false,"value":"c"}
// 测试.html:34 {"done":false,"value":"d"}
// 测试.html:35 {"done":true}

大部分步骤一致,只是在函数前加上[Symbol.iterator]:
而可迭代对象可以使用for of进行遍历
如下

for(let item of myObj1){
    console.log(item);
}
//输出同样效果

当自定义类复杂时,自制迭代器也就更难写


网站公告

今日签到

点亮在社区的每一天
去签到