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())
相关推荐
偷光2 小时前
浏览器中的隐藏IDE: Elements (元素) 面板
开发语言·前端·ide·php
江拥羡橙6 小时前
Vue和React怎么选?全面比对
前端·vue.js·react.js
千码君20166 小时前
React Native:快速熟悉react 语法和企业级开发
javascript·react native·react.js·vite·hook
楼田莉子8 小时前
Qt开发学习——QtCreator深度介绍/程序运行/开发规范/对象树
开发语言·前端·c++·qt·学习
暮之沧蓝8 小时前
Vue总结
前端·javascript·vue.js
木易 士心9 小时前
Promise深度解析:前端异步编程的核心
前端·javascript
im_AMBER9 小时前
Web 开发 21
前端·学习
又是忙碌的一天9 小时前
前端学习day01
前端·学习·html
Joker Zxc9 小时前
【前端基础】20、CSS属性——transform、translate、transition
前端·css
excel9 小时前
深入解析 Vue 3 源码:computed 的底层实现原理
前端·javascript·vue.js