建立JavaScript的雜湊表Hashtable

來源:互聯網
上載者:User

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 進行擴充。

聯繫我們

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