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())
相关推荐
LaughingZhu28 分钟前
Product Hunt 每日热榜 | 2026-05-21
前端·人工智能·经验分享·chatgpt·html
怕浪猫35 分钟前
Electron 开发实战(一):从零入门核心基础与环境搭建
前端·electron·ai编程
小鹏linux1 小时前
Ubuntu 22.04 部署开源免费具有精美现代web页面的Casdoor账号管理系统
linux·前端·ubuntu·开源·堡垒机
前端若水2 小时前
会话管理:创建、切换、删除对话历史
前端·人工智能·python·react.js
Bigger2 小时前
mini-cc:一个轻量级 AI 编程助手的诞生
前端·ai编程·claude
涵涵(互关)3 小时前
Naive-ui树型选择器只显示根节点
前端·ui·vue
BY组态3 小时前
Ricon组态系统最佳实践:从零开始构建物联网监控平台
前端·物联网·iot·web组态·组态
BY组态3 小时前
Ricon组态系统vs传统组态软件:为什么选择新一代Web组态平台
前端·物联网·iot·web组态·组态
SoaringHeart3 小时前
Flutter进阶:OverlayEntry 插入图层管理器 NOverlayZIndexManager
前端·flutter
放下华子我只抽RuiKe53 小时前
React 从入门到生产(四):自定义 Hook
前端·javascript·人工智能·深度学习·react.js·自然语言处理·前端框架