• 在JavaScript 自定义对象来模拟Java中的Map


    直接看代码:

     1 //模拟一个Map对象
     2 function Map(){
     3     
     4     //声明一个容器            
     5     var container={};
     6     
     7     //定义一个put方法,向容器中存值
     8     this.put=function(key,value){
     9         container[key]=value;
    10     }
    11     
    12     //通过key获取value
    13     this.get=function(key){
    14         if(container[key] || container[key]===0 || container[key]===false){
    15             return container[key]
    16         }else{
    17             return null;
    18         }
    19     }
    20     
    21     //获取map中存入键值对的个数
    22     this.size=function(){
    23         var count=0;
    24         //遍历对象属性
    25         for(var attr in container){
    26             count++;
    27         }
    28         return count;
    29     }
    30     
    31     //遍历map并传入一个回调函数,该函数有2个参数,一个接收key,一个接收value
    32     this.each=function(callback){
    33         for(var attr in container){
    34             callback(attr,container[attr]);
    35         }
    36     }
    37     
    38     //从map中删除数据
    39     this.remove=function(key){
    40         delete container[key];
    41     }
    42 }

    代码测试:

     1 //通过put存值
     2 var map=new Map();
     3 
     4 map.put("name","caoyc");
     5 map.put("age",25);
     6 map.put("phone","13700000000");
     7 
     8 //通过get获取值
     9 document.write("1:通过get方法获取值<br/>");  
    10 document.write("name:"+map.get("name"));  
    11 document.write("<hr/>");  
    12 
    13 //获取map中存入键值对的个数
    14 document.write("2:获取map中存入键值对的个值<br/>");  
    15 document.write("size:"+map.size());  
    16 document.write("<hr/>"); 
    17 
    18 //使用回调函数遍历map
    19 document.write("3:使用回调函数遍历map<br/>");  
    20 map.each(function(key,value){
    21         document.write(key+":"+value);
    22         document.write("<br/>");
    23     });  
    24 document.write("<hr/>");
    25 
    26 //使用remove删除数据
    27 document.write("4:使用remove删除数据<br/>");  
    28 map.remove("name");
    29 document.write("删除后再次遍历map<br/>");  
    30 map.each(function(key,value){
    31         document.write(key+":"+value);
    32         document.write("<br/>");
    33     });  
    34 document.write("<hr/>");

    最终输出结果:

  • 相关阅读:
    移动端布局方案汇总&&原理解析
    Javascript运行机制
    git 使用
    async await详解
    vue使用axios调用豆瓣API跨域问题
    hash和history的区别
    http状态码
    XSS 和 CSRF简述及预防措施
    【pytorch】pytorch基础学习
    [源码解读] ResNet源码解读(pytorch)
  • 原文地址:https://www.cnblogs.com/caoyc/p/5723658.html
Copyright © 2020-2023  润新知