视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
创建JavaScript的哈希表Hashtable
2020-11-27 20:30:34 责编:小采
文档


Hashtable是最常用的数据结构之一,但在JavaScript里没有各种数据结构对象。但是我们可以利用动态语言的一些特性来实现一些常用的数据结构和操作,这样可以使一些复杂的代码逻辑更清晰,也更符合面象对象编程所提倡的封装原则。这里其实就是利用JavaScriptObject 对象可以动态添加属性的特性来实现Hashtable, 这里有需要说明的是JavaScript 可以通过for语句来遍历Object中的所有属性。但是这个方法一般情况下应当尽量避免使用,除非你真的知道你的对象中放了些什么。

<script type="text/javascript">
function Hashtable() { 
 this._hashValue= new Object(); 
 this._iCount= 0; 
} 
 
Hashtable.prototype.add = function(strKey, value) { 
 if(typeof (strKey) == "string"){ 
 this._hashValue[strKey]= typeof (value) != "undefined"? value : null; 
 this._iCount++; 
 returntrue; 
 } 
 else 
 throw"hash key not allow null!"; 
} 
 
Hashtable.prototype.get = function (key) { 
 if (typeof (key)== "string" && this._hashValue[key] != typeof('undefined')) { 
 returnthis._hashValue[key]; 
 } 
 if(typeof (key) == "number") 
 returnthis._getCellByIndex(key); 
 else 
 throw"hash value not allow null!"; 
 
 returnnull; 
} 
 
Hashtable.prototype.contain = function(key) { 
 returnthis.get(key) != null; 
} 
 
Hashtable.prototype.findKey = function(iIndex) { 
 if(typeof (iIndex) == "number") 
 returnthis._getCellByIndex(iIndex, false); 
 else 
 throw"find key parameter must be a number!"; 
} 
 
Hashtable.prototype.count = function () { 
 returnthis._iCount; 
} 
 
Hashtable.prototype._getCellByIndex = function(iIndex, bIsGetValue) { 
 vari = 0; 
 if(bIsGetValue == null) bIsGetValue = true; 
 for(var key in this._hashValue) { 
 if(i == iIndex) { 
 returnbIsGetValue ? this._hashValue[key] : key; 
 } 
 i++; 
 } 
 returnnull; 
} 
 
Hashtable.prototype.remove = function(key) { 
 for(var strKey in this._hashValue) { 
 if(key == strKey) 
 { 
 deletethis._hashValue[key]; 
 this._iCount--; 
 } 
 } 
} 
 
Hashtable.prototype.clear = function () { 
 for (var key in this._hashValue) { 
 delete this._hashValue[key]; 
 } 
 this._iCount = 0; 
} 
</script>

StringCollection/ArrayList/Stack/Queue等等都可以借鉴这个思路来对JavaScript 进行扩展。

下载本文
显示全文
专题