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 } www.aiwalls.com
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 進行擴展。
摘自 十一月的雨