我知道的JavaScript–資料結構之– Hashtable

來源:互聯網
上載者:User
 1 function Hashtable() {  
2 this._hashValue= new Object();
3 this._iCount= 0;
4 }
5 Hashtable.prototype.add = function(strKey, value) {
6 if(typeof (strKey) == "string"){
7 this._hashValue[strKey]= typeof (value) != "undefined"? value : null;
8 this._iCount++;
9 returntrue;
10 }
11 else
12 throw"hash key not allow null!";
13 }
14 Hashtable.prototype.get = function (key) {
15 if (typeof (key)== "string" && this._hashValue[key] != typeof('undefined')) {
16 returnthis._hashValue[key];
17 }
18 if(typeof (key) == "number")
19 returnthis._getCellByIndex(key);
20 else
21 throw"hash value not allow null!";
22
23 returnnull;
24 }
25 Hashtable.prototype.contain = function(key) {
26 returnthis.get(key) != null;
27 }
28 Hashtable.prototype.findKey = function(iIndex) {
29 if(typeof (iIndex) == "number")
30 returnthis._getCellByIndex(iIndex, false);
31 else
32 throw"find key parameter must be a number!";
33 }
34 Hashtable.prototype.count = function () {
35 returnthis._iCount;
36 }
37 Hashtable.prototype._getCellByIndex = function(iIndex, bIsGetValue) {
38 vari = 0;
39 if(bIsGetValue == null) bIsGetValue = true;
40 for(var key in this._hashValue) {
41 if(i == iIndex) {
42 returnbIsGetValue ? this._hashValue[key] : key;
43 }
44 i++;
45 }
46 returnnull;
47 }
48 Hashtable.prototype.remove = function(key) {
49 for(var strKey in this._hashValue) {
50 if(key == strKey) {
51 deletethis._hashValue[key];
52 this._iCount--;
53 }
54 }
55 }
56 Hashtable.prototype.clear = function () {
57 for (var key in this._hashValue) {
58 delete this._hashValue[key];
59 }
60 this._iCount = 0;
61 }

解釋:Hashtable在c#中是最常用的資料結構之一,但在JavaScript 裡沒有各種資料結構對象。但是我們可以利用動態語言的一些特性來實現一些常用的資料結構和操作,這樣可以使一些複雜的代碼邏輯更清晰,也更符合面象對象編程所提倡的封裝原則。這裡其實就是利用JavaScriptObject 對象可以動態添加屬性的特性來實現Hashtable, 這裡有需要說明的是JavaScript 可以通過for語句來遍曆Object中的所有屬性。但是這個方法一般情況下應當盡量避免使用,除非你真的知道你的對象中放了些什麼。 

[By the way]: StringCollection/ArrayList/Stack/Queue等等都可以借鑒這個思路來對JavaScript 進行擴充。 

 

轉載請註明出處:http://www.cnblogs.com/RobbinHan/archive/2011/12/05/2270707.html 

本文作者: 十一月的雨 http://www.cnblogs.com/RobbinHan

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.