`
280862132
  • 浏览: 84051 次
  • 性别: Icon_minigender_1
  • 来自: 重庆
社区版块
存档分类
最新评论

JS之HashMap

    博客分类:
  • JS
阅读更多
<script language="javascript">
function HashMap(){
/**Map大小**/
var size=0;
/**对象**/
var entry=new Object();
/**Map的存put方法**/
this.put=function(key,value){
if(!this.containsKey(key)){
size++;
entry[key]=value;
}
}
/**Map取get方法**/
this.get=function(key){
return this.containsKey(key) ? entry[key] : null;
}
/**Map删除remove方法**/
this.remove=function(key){
if(this.containsKey(key) && ( delete entry[key] )){
size--;
}
}
/**是否包含Key**/
this.containsKey= function (key){
return (key in entry);
}
/**是否包含Value**/
this.containsValue=function(value){
for(var prop in entry)
{
if(entry[prop]==value){
return true;
}
}
return false;
}
/**所有的Value**/
this.values=function(){
var values=new Array();
for(var prop in entry)
{
values.push(entry[prop]);
}
return values;
}
/**所有的 Key**/
this.keys=function(){
var keys=new Array();
for(var prop in entry)
{
keys.push(prop);
}
return keys;
}
/**Map size**/
this.size=function(){
return size;
}
/**清空Map**/
this.clear=function(){
size=0;
entry=new Object();
}

}
//创建HashMap对象
var hashMap=new HashMap();
  hashMap.put("A","1");
  hashMap.put("B","2");
  hashMap.put("A","5");
  hashMap.put("C","3");
  hashMap.put("A","4");
alert(hashMap.size());

</script>
感谢huangpengxiao给我的帮助(http://huangpengxiao.iteye.com/blog/96718)
分享到:
评论
1 楼 H_kx 2016-08-12  
put()方法有个bug, 无法覆盖已有的key-value
修改如下:

/**Map的存put方法**/
this.put=function(key,value){
  if(!this.containsKey(key)){
      size++;
  }
  entry[key]=value;
}

相关推荐

Global site tag (gtag.js) - Google Analytics