標籤:c a get 資料 使用 set
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();