js迭代器

文章目录


前言

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

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

实现原理:

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

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

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

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

javascript 复制代码
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会向后移动,直至遍历完毕

调用迭代器

语法

javascript 复制代码
const a=可迭代对象[Symbol.iterator]()

实例如下

javascript 复制代码
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}

自制迭代器

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

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

javascript 复制代码
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进行遍历

如下

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

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

相关推荐
Tian_Hang12 分钟前
C++原型模式(Protype)
开发语言·c++·算法
天天讯通19 分钟前
OKCC 呼叫中心安全性能全解析:技术防护与管理措施指南
大数据·开发语言·网络·人工智能·安全·语音识别
xufengzhu42 分钟前
第三方 Python 库 redis-py + hiredis 的使用
开发语言·redis·python
黄敬峰1 小时前
从 DFS 遍历到抖音推荐算法:前端工程师的硬核复习笔记
前端
zach1 小时前
网页中的虚拟滚动技术是不是源自IOS中的tableview的机制
前端
林希_Rachel_傻希希1 小时前
1小时速通React之Hooks
前端·javascript·面试
柯克七七1 小时前
公司前端项目打包体积从 2MB 降到 400KB,我改了这四个配置
前端
英勇无比的消炎药1 小时前
我才发现这些架构的“拆”与“合”哲学
前端
jingling5551 小时前
go | 环境安装和快速入门
开发语言·后端·golang