當(dāng)前位置:軟件學(xué)堂 > 資訊首頁 > 網(wǎng)絡(luò)編程 > 編程其他 > JavaScript制作哈希表

JavaScript制作哈希表

2012/11/12 15:45:35作者:佚名來源:網(wǎng)絡(luò)

移動端

【實例名稱】

JavaScript制作哈希表

【實例描述】

在保存數(shù)據(jù)時,使用哈希表可以存儲不同數(shù)據(jù)類型的值。本例通過JavaScript創(chuàng)建一個哈希表,學(xué)習(xí)如何保存數(shù)據(jù)字典(鍵/值對)。

【實例代碼】

<html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>標(biāo)題頁-學(xué)無憂(www.yzddtk.cn)</title> <SCRIPT LANGUAGE="JavaScript"> //自定義哈希表類 function Hashtable() {     this._hash = new Object();  // 創(chuàng)建Object對象     //哈希表的添加方法     this.add = function(key,value){                 if(typeof(key)!="undefined"){                     if(this.contains(key)==false){                           this._hash[key]=typeof(value)=="undefined"?null:value;                           return true;                     } else {                            return false;                     }                 } else {                           return false;                 }             }     //哈希表的移除方法     this.remove = function(key){delete this._hash[key];}     //哈希表內(nèi)部鍵的數(shù)量     this.count = function(){var i=0;for(var k in this._hash){i++;} return i;}    //通過鍵值獲取哈希表的值     this.items = function(key){return this._hash[key];}     //在哈希表中判斷某個值是否存在     this.contains  = function(key){ return typeof(this._hash[key])!="undefined";}     //清空哈希表內(nèi)容的方法     this.clear = function(){for(var k in this._hash){delete this._hash[k];}}

} var myhash=new Hashtable();   //創(chuàng)建哈希表 myhash.add("name","張三");    //添加鍵和值 alert(myhash.item["name"]);   //根據(jù)指定鍵顯示哈希表的值 </script> </head> <body> </body> </html>

 

【運行效果】

 

【難點剖析】

本例的重點是如何創(chuàng)建哈希表的默認(rèn)方法,如增加鍵值對、移除鍵值對、查詢鍵值等。這些都通過“function”方法實現(xiàn)。要了解哈希表的構(gòu)造,請參考相關(guān)資料。

【源碼下載】

為了JS代碼的準(zhǔn)確性,請點擊:JavaScript制作哈希表 進(jìn)行本實例源碼下載 

標(biāo)簽: JavaScript  表格