当前位置:编程学习 > JAVA >>

我知道的JavaScript -- 数据结构之– Hashtable

 

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.zzzyk.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 进行扩展。

  

摘自 十一月的雨

补充:web前端 , JavaScript ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,