zoukankan      html  css  js  c++  java
  • Iterator接口

    1.Iterator的作用:对不同的数据进行遍历
    2.Symbol.iterator的部署
    3.for of能遍历的数据:数组,字符串,argument,set,map

    let arr = ['tom','mickey','minnie'];
    for(let value of arr){
        console.log(value)
    }
    
    
    let mSet = new Set(arr);
    for(let value of mSet){
        console.log(value);
    }
    console.log(arr,mSet)
    
    
    let obj = {
        name:'mickey',
        age:10,
        psw:'123'
    }
    for(let filed of obj){
        console.log(filed);//报错,没有iterator接口
    }
    console.log(obj)
    
    
    let arr = ['tom','mickey','minnie'];
    
    调用容器的symbol.iterator方法,并调用,获取容器的迭代器对象
    会产生一个指针,指向容器的第一个值
    let ite = arr[Symbol.iterator]()
    每次调用迭代器的next()方法时,都会返回容器中的下一个值是否遍历结束:done:false 结束了:done:true
    console.log(ite.next())
    console.log(ite.next())
    console.log(ite.next())
    console.log(ite.next())
    
    
    //obj自定义添加iterator方法
    function myIterator(arr){
        let arrIndex = 0;
        return{
            next(){
    
                if( arrIndex < arr.length ){
                    return{
                        value:arr[arrIndex++],
                        done:false
                    }
                }else{
                    return{
                        value:undefined,
                        done:true
                    }
                }
    
            }
        }
    }
    
    let mIte = myIterator(arr);
    console.log(mIte.next());
    console.log(mIte.next());
    console.log(mIte.next());
    console.log(mIte.next());

     

     

     

  • 相关阅读:
    Python将字符串转换成字典
    MySQL索引、视图
    MySQL高级查询
    MySQL函数应用
    MySQL约束
    MySQL基础查询
    MySQL数据库基本语法
    MySQL数据库存储引擎
    MySQL数据库简介与命令行操作
    MySQL 安装和配置环境变量
  • 原文地址:https://www.cnblogs.com/lisa2544/p/15654632.html
Copyright © 2011-2022 走看看