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())
相关推荐
前端炒粉40 分钟前
35.LRU 缓存
开发语言·javascript·数据结构·算法·缓存·js
巧克力芋泥包2 小时前
前端使用阿里云图形验证码;并且与安卓进行交互
android·前端·阿里云
G***E3163 小时前
前端GraphQLAPI
前端
lumi.3 小时前
Vue + Element Plus 实现AI文档解析与问答功能(含详细注释+核心逻辑解析)
前端·javascript·vue.js·人工智能
z***I3943 小时前
VueGraphQLAPI
前端
S***t7144 小时前
Vue面试经验
javascript·vue.js·面试
粉末的沉淀5 小时前
css:制作带边框的气泡框
前端·javascript·css
p***h6436 小时前
JavaScript在Node.js中的异步编程
开发语言·javascript·node.js
N***73856 小时前
Vue网络编程详解
前端·javascript·vue.js
e***71676 小时前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端