ES6基础----iterator接口的使用

iterator一个统一规范接口,作用是为了给复杂的数据提供一个统一遍历的方法。

1、所有实现[Symbol.iterator]属性的数据都可以使用for...of进行遍历

// const arr=["内容1","内容2","内容3"]//----有 Symbols 属性及可以进行 iterator 遍历

// console.log(arr)

2、进行 Sysbols 遍历

// let arr02=arr[Symbol.iterator]();

// console.log(arr02.next())//{value: '内容1', done: false} --- 值 是否后面没有值(返回 false / true)

// console.log(arr02.next())//{value: '内容2', done: false}

// console.log(arr02.next())//{value: '内容3', done: false}

// console.log(arr02.next())//{value: undefined, done: true}

3、如果一个数据结构想要使用for...of循环 ---对象中想用遍历

但是自身没有[Symbol.iterator]属性 ,就可以进行添加[Symbol.iterator],实现for...of循环

    //对象中有数组

        const obj={

            arr:[1,2,3],

            [Symbol.iterator](){

                let index=0

                return{

                    next:function(){

                        return index<obj.arr.length

                        ?{value:obj.arr[index++],done:false}

                        :{value:undefined,done:true}

                    }

                }

            }

        }

        let obj2=obj[Symbol.iterator]()

        console.log(obj2.next())//{value: 1, done: false}

        console.log(obj2.next())//{value: 2, done: false}

        console.log(obj2.next())//{value: 3, done: false}

        console.log(obj2.next())//{value: undefined, done: true}

        for(let a of obj){

            console.log(a)//1  2  3

        }


  //对象中纯对象

         const obj3={

             name:"张三",

            age:20,

            address:"昆明市",

            [Symbol.iterator](){

                let index=Object.keys(obj3);

                //Object.keys得到所有的key,但是是一个数组

               //['name', 'age', 'address']

                 let nextindex=0

                 return{

                    next:function(){

                        return{value:obj3[index[nextindex++]],

                            done:nextindex>index.length}

                    }

                }

             }

         }

        let obj4=obj3[Symbol.iterator]()

        console.log(obj4.next())//

         console.log(obj4.next())

         console.log(obj4.next())

         console.log(obj4.next())
相关推荐
十八朵郁金香20 分钟前
通俗易懂的DOM1级标准介绍
开发语言·前端·javascript
GDAL1 小时前
HTML 中的 Canvas 样式设置全解
javascript
m0_528723811 小时前
HTML中,title和h1标签的区别是什么?
前端·html
Dark_programmer1 小时前
html - - - - - modal弹窗出现时,页面怎么能限制滚动
前端·html
GDAL1 小时前
HTML Canvas clip 深入全面讲解
前端·javascript·canvas
禾苗种树2 小时前
在 Vue 3 中使用 ECharts 制作多 Y 轴折线图时,若希望 **Y 轴颜色自动匹配折线颜色**且无需手动干预,可以通过以下步骤实现:
前端·vue.js·echarts
GISer_Jing2 小时前
Javascript排序算法(冒泡排序、快速排序、选择排序、堆排序、插入排序、希尔排序)详解
javascript·算法·排序算法
贵州数擎科技有限公司2 小时前
使用 Three.js 实现流光特效
前端·webgl
JustHappy2 小时前
「我们一起做组件库🌻」做个面包屑🥖,Vue的依赖注入实战💉(VersakitUI开发实录)
前端·javascript·github
祝鹏2 小时前
前端如何制定监控项
前端