js實現HashTable

來源:互聯網
上載者:User

標籤: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();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.