看到一篇关于js 实现hashtable 的文章http://www.blogjava.net/fantasy/archive/2006/08/02/44742.html#61363
,挺不错,考虑到现在很多网友都使用prototype开发,所以我用prototype的方式重新实现了这个hashtable 集合,并修正了一个小bug (hashtable中删除对象前先判断存在)。
//hashtable in javascript
var Collections = new Object();
Collections.Base = Class.create();
Collections.Base.prototype = {
initialize:function()
{
this.count = 0 ;
this.container = new Object();
}
}
Collections.Hashtable = Class.create();
Collections.Hashtable.prototype = Object.extend(new Collections.Base(),
{
add:function(key ,value)
{
if(!this.containsKey(key))
{
this.count++;
}
this.container[key] = value;
},
get:function(key)
{
if(this.containsKey(key))
{
return this.container[key];
}
else
{
return null;
}
},
containsKey:function(key)
{
return (key in this.container);
},
containsValue:function(value)
{
for(var prop in this.container)
{
if(this.container[prop]==value)
{
return true;
}
}
return false;
},
keys:function()
{
var keys = new Array();
for(var prop in this.container)
{
keys.push(prop);
}
return keys;
},
values:function()
{
var values = new Array();
for(var prop in this.container)
{
values.push(this.container[prop]);
}
return values;
},
remove:function()
{
if(this.containsKey(key))
{
delete this.container[key];
this.count--;
}
}
}
);
调用方式可以如下
var ht = new Collections.Hashtable();
ht.add("guest1" ,"Jackson");
ht.add("guest2" ,"Tom");
取值
var name = ht.get("guest1");
其他方法应该比较直观,不用多说了,呵呵!