创建JavaScript的哈希表Hashtable

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

原文地址:https://www.cnblogs.com/xiaoyang002/p/4092626.html