首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

HashMap的JavaScript简要实现

2012-11-06 
HashMap的JavaScript简洁实现今天在工作中碰到一个问题,需要在JavaScript使用类似Java的HashMap的数据类型

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 SmithhashMap.Contains("title");//falsehashMap.Contains("name");//truehashMap.Remove("age");

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

热点排行