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())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值