日期:2014-05-16  浏览次数:20388 次

HashMap的JavaScript简洁实现
今天在工作中碰到一个问题,需要在JavaScript使用类似Java的HashMap的数据类型,可惜JavaScript自身不提供这种数据类型,于是想自己实现一个。
在Google上搜到一个老外论坛(http://www.hftonline.com/forum/showthread.php?t=12882)上的实现方式,感觉非常简洁明了,于是按照他的思路,扩充了一下,加了两个自己想要的方法,用着蛮爽。
var hashMap = {
    Set : function(key,value){this[key] = value},
    Get : function(key){return this[key]},
    Contains : function(key){return this.Get(key) == null?false:true},
    Remove : function(key){delete this[key]}
}

使用方法示例:
hashMap.Set("name","John Smith");
hashMap.Set("age",24);
hashMap.Get("name");//John Smith
hashMap.Contains("title");//false
hashMap.Contains("name");//true
hashMap.Remove("age");

够简洁吧。而且比用数组方式实现更好的地方在于,不会出现数组越界错误。
1 楼 zhulongxing_sz 2012-09-04  
Good!!正是我想要的,楼主真赞~~~