`
ben_hu
  • 浏览: 92200 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

JavaScript实现Map数据结构

阅读更多
function Map(){
   this.map    =  new Object();
   this.length = 0;
  
   this.size = function(){
       return this.length;
   }
  
   this.put = function(key, value){
     
      if( !this.map['_' + key])
        {
             ++this.length;
        }
     
      this.map['_' + key] = value;
    
   }
  
   this.remove = function(key){
      
       if(this.map['_' + key])
      {
         
          --this.length;
        return delete this.map['_' + key];
      }
      else
      {
          return false;
      }
   }
  
   this.containsKey = function(key){
   
     return this.map['_' + key] ? true:false;
  
   }
   
   this.get = function(key){   
 
      return this.map['_' + key] ? this.map['_' + key]:null;
 
   }


 this.inspect=function(){   
     var str = '';
    
     for(var each in this.map)
     {
          str+= '\n'+ each + '  Value:'+ this.map[each];
     }
    
     return str;
   }
    
}

------------------------------------------
测试程序

//测试Map的调用方法

function testMap(){
   var testmap=new Map();
   alert("cur size:" + testmap.size());
    alert("get bu cunzai:" + testmap.get("bu cunzai"));
   testmap.put("01","michael");
    testmap.put("01","michael1");
     testmap.put("01","michael11");
      testmap.put("01","michael1111");
       testmap.put("011","michael1111");
        testmap.put("object",new Array());
        testmap.put("number",1234);
        testmap.put(78944444444444444422222222222222,1234);
        testmap.put("function",function(num){return num;});
      
        //alert("function:"+ testmap.get("function")(789));
        alert("function:"+ testmap.get("function")(78944444444444444422222222222222));
   alert ("cur size:" + testmap.size() + "inspect:" + testmap.inspect());
    alert("remove function:" + testmap.remove("function"));
    alert("remove object:" + testmap.remove("object"));
   testmap.put("02","michael2");
   testmap.put("022","achang2");
   testmap.put("022","achang3");
   alert ("cur size:" + testmap.size() + "inspect:" + testmap.inspect());
  
 
   var key="02"
   
   if (testmap.containsKey(key)){
       var value=testmap.get(key);
       alert ("02 first|"+value);
   }else{
       alert("no Cotain" + key);
   }
 
  alert("remove:" + testmap.remove("02"));
  alert("cur size:" + testmap.size());
  alert( testmap.remove("0000002"));
  alert("cur size:" + testmap.size());
  alert("contain:" + testmap.containsKey("0000002"));
  
  if (testmap.containsKey(key)){
       var value=testmap.get(key);
       alert ("02 |"+ value);
   }else{
       alert ("no Contain:"+key);
   }
 
  

}
testMap();
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics