当前位置:网站首页>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);
}
边栏推荐
- 页面加载流程
- 微信小程序云开发之券码领取,怎么防止用户领取到相同的数据?
- 【 application 】 life many years of operations, what turned scored 12 k + annual bonus salary?
- Phospholipid-Polyethylene Glycol-Aldehyde DSPE-PEG-Aldehyde DSPE-PEG-CHO MW: 5000
- 三月底啦啦
- --fs module--
- Cut out web icons through PS 2021
- 微信小程序云开发之模糊搜索
- --fs模块--
- Phospholipid-polyethylene glycol-thiol, DSPE-PEG-Thiol, DSPE-PEG-SH, MW: 5000
猜你喜欢

微信小程序怎么批量生成带参数的小程序码?

STM32 触发HardFault_Handler如何查找原因

新工程加载YOLOV6的预训练权重问题

js basics

Phospholipid-polyethylene glycol-targeted neovascularization targeting peptide APRPG, DSPE-PEG-APRPG

【手把手带你学nRF52832/nRF52840 · (1)开发环境搭建】

Small program van-cell line wrapping can be left-aligned

npm--package.json---require

Deveco studio Hongmeng app access network detailed process (js)

Advanced gradient of skeleton effect, suitable for waiting for pictures
随机推荐
Source Insight 使用教程(2)——常用功能
DSPE-PEG-PDP, DSPE-PEG-OPSS, phospholipid-polyethylene glycol-mercaptopyridine supply, MW: 5000
Circular linked list---------Joseph problem
SOCKS5
Error in render: “TypeError: Cannot read properties of null (reading ‘0‘)“ 报错解决方案
C语言 十六进制整数字符串转十进制整数
每日面试题 2022/7/28
Usage of JOIN in MySQL
6.27面试集
C语言入门小游戏—三子棋
debian 10 nat and routing forwarding
String comparison size in MySQL (date string comparison problem)
1.uview form校验位置可以改变 2.时间区间
npm and package.json
Deveco studio Hongmeng app access network detailed process (js)
Phospholipid-polyethylene glycol-thiol, DSPE-PEG-Thiol, DSPE-PEG-SH, MW: 5000
js takes the value of a feature at a certain position in the string, such as Huawei=> Huawei
js basics
PCL—point cloud data segmentation
【 application 】 life many years of operations, what turned scored 12 k + annual bonus salary?