今天在工作中碰到一个问题,需要在JavaScript使用类似Java的HashMap的数据类型,可惜JavaScript自身不提供这种数据类型,于是想自己实现一个。
在Google上搜到一个老外论坛(http://www.hftonline.com/forum/showthread.php?t=12882)上的实现方式,感觉非常简洁明了,于是按照他的思路,扩充了一下,加了两个自己想要的方法,用着蛮爽。
使用方法示例:
够简洁吧。而且比用数组方式实现更好的地方在于,不会出现数组越界错误。
在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]}
- }
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");
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");
够简洁吧。而且比用数组方式实现更好的地方在于,不会出现数组越界错误。