当前位置:网站首页>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);
}
边栏推荐
- 语义分割标签即像素值的巨坑,transforms.ToTensor()的错误使用
- 【 application 】 life many years of operations, what turned scored 12 k + annual bonus salary?
- C语言 void和void *(无类型指针)
- js的“类数组”及“类数组转数组”
- Phospholipid-polyethylene glycol-azide, DSPE-PEG-Azide, DSPE-PEG-N3, MW: 5000
- The querystring module
- kettle 安装与配置
- ---static page---
- 页面加载流程
- C语言 内联函数
猜你喜欢
随机推荐
np.isnan ()
L1-043 阅览室 (20分)
Debian 10 NTP Service Configuration
如何查看一个现有的keil工程之前由什么版本的keil IDE编译
URL模块
[Mianjing] Mihayou data development on one side and two sides
C语言入门小游戏—三子棋
微信小程序怎么批量生成带参数的小程序码?
配置mmdet来训练Swin-Transformer之一配置环境
一分种一起来了解Vite的基础
require模块化语法
我的小笔记 =》其他东东
骨架效果 之高级渐变,适用图片等待时
Advanced gradient of skeleton effect, suitable for waiting for pictures
STM32 CAN过滤器
Cut out web icons through PS 2021
1.6一些今日学习
面试总结 22/7/22 面试中的重点
DSPE-PEG-Silane, DSPE-PEG-SIL, phospholipid-polyethylene glycol-silane modified active group
Questions about your resume