本文介紹了兩種用 JavaScript 模擬 Hashtable 的實現方式,需要的朋友可以參考,希望對大家有所幫助。
由於 JS 沒有原生的哈希表,我們可以借助對象來模擬。第一種實現如下:
<script> function Hashtable()//自定義hashtable { this._hash = new Object(); this.add = function(key, value) { if (typeof (key) != "undefined") { if (this.contains(key) == false) { this._hash[key] = typeof (value) == "undefined" ? null : value; return true; } else { return false; } } else { return false; } } this.remove = function(key) { delete this._hash[key]; } this.count = function() { var i = 0; for (var k in this._hash) { i++; } return i; } this.items = function(key) { return this._hash[key]; } this.contains = function(key) { return typeof (this._hash[key]) != "undefined"; } this.clear = function() { for (var k in this._hash) { delete this._hash[k]; } } } </script>第二種實現借助 hasOwnProperty 判斷鍵是否存在,並維護一個計數器,結構更為清晰:
<script> // js哈希表 function HashTable() { this.ObjArr = {}; this.Count = 0; //添加 this.Add = function(key, value) { if (this.ObjArr.hasOwnProperty(key)) { return false; //如果鍵已經存在,不添加 } else { this.ObjArr[key] = value; this.Count++; return true; } } //是否包含某項 this.Contains = function(key) { return this.ObjArr.hasOwnProperty(key); } //取某一項 其實等價於this.ObjArr[key] this.GetValue = function(key) { if (this.Contains(key)) { return this.ObjArr[key]; } else { throw Error("Hashtable not cotains the key: " + String(key)); //腳本錯誤 } } //移除 this.Remove = function(key) { if (this.Contains(key)) { delete this.ObjArr[key]; this.Count--; } } //清空 this.Clear = function() { this.ObjArr = {}; this.Count = 0; } } </script>測試代碼:
<script> //員工 function employee(id, userName) { this.id = id; this.userName = userName; } function test() { var ht = new HashTable(); var tmpEmployee = null; for (var i = 1; i < 6; i++) { tmpEmployee = new employee(i, "Employee_" + i); ht.Add(i, tmpEmployee); } for (var i = 1; i <= ht.Count; i++) { alert(ht.GetValue(i).userName); //其實等價於ht.ObjArr[i].userName } ht.Remove(1); alert(ht.Contains(1)); //false alert(ht.Contains(2)); //true var result = ht.GetValue(2); if (result != null) { alert("Employee Id:" + result.id + ";UserName:" + result.userName); } ht.Add(2, "這一個key已經存在!"); //Add無效 alert(ht.Count); } </script>兩種實現的核心思想一致:利用 JS 對象的鍵值特性存儲數據,通過 hasOwnProperty 或 typeof 判斷鍵是否存在,並提供 add、remove、contains、count、clear 等操作。需要鍵值映射場景時,這是一個輕量實用的方案。