当前位置:网站首页>ES6迭代器解释举例
ES6迭代器解释举例
2022-08-02 03:24:00 【yorup】
迭代器
迭代器(lterator)是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署lterator接口,就可以完成遍历操作,ES6新增遍历方式for...of。
原生具备lterator接口的数据有:Array,Arguments,Set,Map,String,NodeList。
对象没有迭代器接口,但是我们可以给它加一个,迭代器就是数据类型里面自带的的方法,所以给对象添加一个方法为迭代器接口就可以了
注意不要改变方法的名字。因为for...of只能识别next()方法。
原理:创建一个指针对象,指向数据结构的起始位置,第一次调用==next()==方法,指针自动指向数据结构第一个成员,接下来不断调用next(),指针一直往后移动,直到指向最后一个成员,没调用next()返回一个包含value和done属性的对象.
let arr = ["a","b","c"];
let myIte = arr[Symbol.iterator]();//arr本身就具备迭代器接口,拿到这个iterator接口
console.log(myIte.next());//{value: "a", done: false}
console.log(myIte.next());//{value: "b", done: false}
console.log(myIte.next());//{value: "c", done: false}
console.log(myIte.next());//{value: "undefined", done: true}
const Stu = {
title:"web2209",
persons:["张三","李四","王五"],
[Symbol.iterator](){
let i=0;
return {
next:()=>{
if(i< this.persons.length){
const Obj = {value: this.persons[i], done: false};
i++;
return Obj;
}else{
return {value: undefined, done: true};
}
}
}
}
}
上面为对象添加了迭代器接口方法[Symbol.iterator](),下面是调用,先打印一下
const Myite = Stu[Symbol.iterator]();
console.log(Myite.next());
console.log(Myite.next());
console.log(Myite.next());
console.log(Myite.next());
下面是用for...of遍历对象里面的值
for(let v of Stu){
console.log(v);
}
边栏推荐
- Scientific research reagent DMPE-PEG-Mal dimyristoylphosphatidylethanolamine-polyethylene glycol-maleimide
- ---static page---
- [Learning Records of Boxue Valley] Super summary, share with heart | Software Testing Interface Testing Basics
- 微信小程序云开发之模糊搜索
- 微信小程序自定义swiper轮播图面板指示点|小圆点|进度条
- __dirname
- basic operator
- 每日五道面试题总结 22/7/19
- 广州华为面试总结
- js预编译 GO 和AO
猜你喜欢
Small program van-cell line wrapping can be left-aligned
Phospholipid-polyethylene glycol-targeted neovascularization targeting peptide APRPG, DSPE-PEG-APRPG
1.uview form校验位置可以改变 2.时间区间
Deveco studio Hongmeng app access network detailed process (js)
小程序 van-cell 换行能左对齐问题
STM32 CAN过滤器
js __proto__、prototype、constructor的关系
uniapp | 使用npm update更新后编译报错问题
简单黑马头条项目
我的小笔记 =》其他东东
随机推荐
每天填坑,精卫填坑第二集,TX1 配置从固态启动,安装Pytorch
js作用域与闭包
js takes the value of a feature at a certain position in the string, such as Huawei=> Huawei
解决glob()返回文件排序不一致问题&onnx本地按照安装方法
display,visibility,opacity
DOM操作---放大镜案例
1.6一些今日学习
相对路径和绝对路径
微信小程序九宫格抽奖和转盘抽奖的实现
URL模块
ModuleNotFoundError No module named 'xxx' possible solutions
微信小程序云开发之券码领取,怎么防止用户领取到相同的数据?
js eventLoop 事件循环机制
函数提升和变量提升
---static page---
Questions about your resume
【 application 】 life many years of operations, what turned scored 12 k + annual bonus salary?
Advanced gradient of skeleton effect, suitable for waiting for pictures
正则笔记(2)- 正则表达式位置匹配攻略
--fs module--