iterator接口

简单总结一下:es6提供了一个iterator接口,并将接口部署到不同的数据结构上(数组、字符串、arguments对象、set、map数据结构)
特点:可以用for…of…循环遍历

概念

iterator是一个接口机制,为各种不同的数据结构提供统一的访问机制

作用

概念:iterator是一个接口机制,为各种不同的数据结构提供统一的访问机制
作用:
1、为各种数据结构提供一个统一的、简便的访问接口
2、使数据结构的成员能够按照某种次序排列
3、ES6创造了一种新的遍历命令 for…of…,iterator接口主要提供for…of…循环

工作原理

工作原理
1、创建一个指针对象(遍历器对象),指向数据结构的起始位置
2、第一次调用next方法,指针自动指向数据结构的第一个成员
3、接下来不断调用next方法,知道最后一个成员
4、每调用next方法返回的是一个包含value和done的对象(value:当前成员的值,done:布尔值)
当遍历结束时返回的value值是undefined done的值是false

                //模拟指针对象(遍历器对象)  底层实现
                function myIterator(arr){
                    var nextIndex=0
                    return {//遍历器对象
                         next:function(){
                             return nextIndex<arr.length?{value:arr[nextIndex++],done:false}:{value:undefined,done:true}                             
                         }
                    }
                }
                //准备一个数据
                let arr=[1,2,"ah"]
                let iteratorobj=myIterator(arr) 
                console.log(iteratorobj.next())  //{value: 1, done: false}
                console.log(iteratorobj.next())  //{value: 2, done: false}
                console.log(iteratorobj.next())  //{value: "ah", done: false}
                console.log(iteratorobj.next())  // {value: undefined, done: true}

//存在iterator接口部署到指定接口上,可以使用for..of..去循环遍历
//数字,字符串,arguments对象,set和map数据结构

                let arr1=[1,2,4,56,67,34]
                for(let i of arr1){
                    console.log(i)
                }

                let str="sdgcbisd"
                for(let i of str){
                    console.log(i)
                }
            
                function fn(){
                    for(let i of arguments){
                        console.log(i)
                    }
                } 
                fn("we","asc",34,34)



                let obj={name:"zhangsan",age:5}
                for(let i of obj){
                    console.log(i)      //iterator.html:69 Uncaught TypeError: obj is not iterable
                }

//等同于在指定的数据结构上部署了iterator
//当使用for of 去循环某一个数据结构时,首先去找Symbol.iterator找到了就去遍历
                let targetData={
                    [Symbol.iterator]:function(){
                        var nextIndex=0
                        return {//遍历器对象
                             next:function(){
                                  return nextIndex<this.length?{value:this[nextIndex++],done:false}:{value:undefined,done:true}                             
                             }
                        }
                    }
                }
// 小扩展   三点运算符  解构赋值默认调用了iterator接口
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值