论坛首页 入门技术论坛

HashMap的JavaScript简洁实现

浏览 1736 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-12-15   最后修改:2009-03-30
今天在工作中碰到一个问题,需要在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");

够简洁吧。而且比用数组方式实现更好的地方在于,不会出现数组越界错误。
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics