栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

JavaScript中实现Map的示例代码

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript中实现Map的示例代码

不废话了,直接贴代码了。

代码一:

var map=new Map();
map.put("a","A");map.put("b","B");map.put("c","C");
map.get("a"); //返回:A
map.entrySet() // 返回Entity[{key,value},{key,value}]
map.containsKey('kevin') //返回:false
function Map() { 
  this.keys = new Array(); 
  this.data = new Object(); 
   
  this.put = function(key, value) { 
    if(this.data[key] == null){ 
      this.keys.push(key); 
      this.data[key] = value; 
    }else{ 
      this.data[key]=this.data[key]; 
    } 
    return true; 
  }; 
   
  this.get = function(key) { 
    return this.data[key]; 
  }; 
   
  this.remove = function(key) { 
    for(var i=0;i0; 
  }; 
   
  this.toString = function(){ 
    var s = "{"; 
    for(var i=0;ii+1){ 
 s+=',' 
      } 
    } 
    s+="}"; 
    return s; 
  }; 
   
  this.parserStringAndAddMap=function(str){ 
    var count=0; 
    if(str && str.length>0){ 
      str=str.trim(); 
      var startIndex=str.indexOf("{"),endIndex=str.lastIndexOf("}"); 
      if(startIndex!==-1 && endIndex!==-1){ 
 str=str.substring(startIndex+1,endIndex); 
 var arrs= str.split(","); 
 for(var i=0;i0 && kv.indexOf("=")!==-1){ 
     var kv_arr=kv.split("="); 
     if(kv_arr.length==2){ 
if(this.put(kv_arr[0].trim(),kv_arr[1].trim())){ 
  count++; 
}else{ 
  console.error('error: kv:'+kv); 
} 
     } 
   } 
 } 
      }else{ 
 console.log("data error:"+str); 
      } 
    }else{ 
      console.log('data is not empty'); 
    } 
    return count; 
  }; 
} 

代码二:

Array.prototype.remove = function(s) {
  for (var i = 0; i < this.length; i++) {
    if (s == this[i])
      this.splice(i, 1);
  }
}

function Map() {
  
  this.keys = new Array();
  
  this.data = new Object();
  
  this.put = function(key, value) {
    if(this.data[key] == null){
      this.keys.push(key);
    }
    this.data[key] = value;
  };
  
  this.get = function(key) {
    return this.data[key];
  };
  
  this.remove = function(key) {
    this.keys.remove(key);
    this.data[key] = null;
  };
  
  this.each = function(fn){
    if(typeof fn != 'function'){
      return;
    }
    var len = this.keys.length;
    for(var i=0;i


function testMap(){
  var m = new Map();
  m.put('key1','Comtop');
  m.put('key2','南方电网');
  m.put('key3','景新花园');
  alert("init:"+m);
  m.put('key1','康拓普');
  alert("set key1:"+m);
  m.remove("key2");
  alert("remove key2: "+m);
  var s ="";
  m.each(function(key,value,index){
    s += index+":"+ key+"="+value+"n";
  });
  alert(s);
}

以上内容通过两段代码给大家分享了Javascript中实现Map,希望大家喜欢。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/100681.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号