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

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

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

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

// console.log(arr)

2、进行 Sysbols 遍历

// let arr02=arrSymbol.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())
相关推荐
前端混子12 小时前
我用 AI 做了个「禾月小历」,一套代码跑微信小程序和 H5
前端
IT_陈寒12 小时前
Java实战技巧总结:当你的finally块没有执行时会发生什么?
前端·人工智能·后端
小帅不太帅12 小时前
一年一次黑五,为了买软件真省钱,我做了个开源小站
前端·人工智能·github
JavaGuide14 小时前
刚刚,阿里版 Codex 上线了匿名模型 HungerG,无限 Token!
前端·后端
zhanlang021715 小时前
HTML 零基础入门到企业实战全套教程【第九章 9.3】移动端 HTML 基础适配入门
前端·html
用户693717500138415 小时前
AI 帮我写了大半年的代码,我却越来越不会写代码了
前端·后端·github
skywalk816315 小时前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness
彭亚川Allen15 小时前
从零手搓 RAG:用 Elasticsearch 存储与检索向量
前端·后端·面试
jerrywus15 小时前
15 个可以直接安装的 AI Agent Skills:按场景挑
前端·agent·claude
涛涛ing15 小时前
用了三年微前端,我们终于把它拆成了单体应用
前端