js实现HashTable

1.哈希表使用键值对进行的数据储存,在数据的存储位置和它的关键字之间建立一一对应的关系,从而使关键字和结构中的一个唯一的存储位置相对应,所以在检索数据时

 只需要根据这个关系便可以快速定位到要找的数据。

function HashTable(){
this._hash={};
this._count=0;
//添加或更新key
this.put=function(key,value){
if(this._hash.hasOwnProperty(key)){
this._hash[key]=value;
return true;
}
else{
this._hash[key]=value;
this._count++;
return true;
}
}
//获取key指定的值
this.get=function(key){
if(this.containsKey(key)){
return this._hash[key];
}
}
//获取元素个数
this.size=function(){
return this._count;
}
//检查是否为空
this.isEmpty=function(){
if(this._count<=0)return true;
else return false;
}
//检查是否包含指定的key
this.containsKey=function(key){
return this._hash.hasOwnProperty(key);
}
//检查是否包含指定的value
this.containsValue=function(value){
for(var strKey in this._hash){
if(this._hash[strKey]==value){
return true;
}
}
return false;
}
//删除一个key
this.remove=function(key){
delete this._hash[key];
this._count--;
}
//清除所有的key
this.clear=function(){
this._hash={};
this._count=0;
}
//从hashtable 中获取key的集合,以数组的形式返回
this.keySet=function(){
var arrKeySet = [];
var index=0;
for(var strKey in this._hash){
arrKeySet[index++]=strKey;
}
return (arrKeySet.length==0)?null:arrKeySet;
}
//从hashtable中获取value的集合,以数组的形式返回
this.valueSet=function(){
var arrValues=[];
var index=0;
for(var strKey in this._hash){
arrValues[index++]=this._hash[strKey];
}
return (arrValues.length==0)?null:arrValues;
}
}

测试案列:

var ht =new HashTable();
ht.put("key","value");
ht.put("key2","value2");
alert( ht.keySet());
alert( ht.valueSet());
alert(ht.get("key"));
ht.remove("key");
alert(ht.get("key"));
ht.clear();

js实现HashTable,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。