当前位置:网站首页>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
js eventLoop 事件循环机制
我的小笔记 =》其他东东
Phospholipid-polyethylene glycol-targeted neovascularization targeting peptide APRPG, DSPE-PEG-APRPG
配置mmdet来训练Swin-Transformer之一配置环境
[vite] Failed to parse source for import analysis because the content contains invalid JS syntax.
C语言 十六进制整数字符串转十进制整数
Deveco studio Hongmeng app access network detailed process (js)
暴力方法求解(leetcode14)查找字符串数组中的最大公共前缀
解决glob()返回文件排序不一致问题&onnx本地按照安装方法
Living to detect the Adaptive Normalized Representation Learning for GeneralizableFace Anti - Spoofing reading notes
6.24今日学习
js 之 Object.defineProperty()
1.8今日学习
每日五道面试题总结 22/7/19
PCL—point cloud data segmentation
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boo
微信小程序实现文本安全监测
Source Insight 使用教程(2)——常用功能
The usage of json type field in mysql









