複製程式碼如下:
function Hashtable()//自訂hashtable
{
this._hash = new Object();
this.add = 函數(鍵, 值) {
if (typeof (key) != "未定義") {
if (this.contains(key) == false) {
this._hash[key] = typeof (value) == "未定義" ?空:值;
返回真;
} 別的 {
返回假;
}
} 別的 {
返回假;
}
}
this.remove = function(key) { 刪除 this._hash[key]; }
this.count = function() { var i = 0; for (var k in this._hash) { 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) { 刪除 this._hash[k]; } }
}
複製程式碼如下:
// js 哈希表
函數哈希表() {
this.ObjArr = {};
this.Count = 0;
//新增
this.Add = 函數(鍵, 值) {
if (this.ObjArr.hasOwnProperty(key)) {
返回假; //如果鍵已經存在,不加入
}
別的 {
this.ObjArr[鍵] = 值;
this.Count++;
返回真;
}
}
// 是否包含某項
this.Contains = 函數(鍵) {
回傳 this.ObjArr.hasOwnProperty(key);
}
//取某件等價於this.ObjArr[key]
this.GetValue = 函數(鍵){
if (this.Contains(key)) {
返回 this.ObjArr[key];
}
別的 {
throw Error("哈希表不包含鍵:" + String(key)); //錯誤腳本
//返回;
}
}
// 刪除
this.Remove = 函數(鍵){
if (this.Contains(key)) {
刪除 this.ObjArr[key];
this.Count--;
}
}
//清空
this.Clear = 函數() {
this.ObjArr = {}; this.Count = 0;
}
}
測試程式碼:
// 員工
函數員工(id,使用者名稱){
這個.id = id;
this.userName = 使用者名稱;
}
函數測試() {
var ht = new HashTable();
var tmpEmployee = null;
for (var i = 1; i < 6; i++) {
tmpEmployee = 新進員工(i, "Employee_" + i);
ht.Add(i, tmpEmployee);
}
for (var i = 1; i <= ht.Count; i++) {
警報(ht.GetValue(i).userName); //其實等價於ht.ObjArr[i].userName
//alert(ht.ObjArr[i].userName);
}
ht.刪除(1);
警報(ht.包含(1)); //錯誤的
警報(ht.包含(2)); //真的
//警報(ht.GetValue(1)); //異常
var 結果 = ht.GetValue(2);
如果(結果!= null){
Alert("員工 ID:" + result.id + ";使用者名稱:" + result.userName);
}
ht.Add(2, "這一個鍵已經存在!"); //新增無效
//ht.Clear(); //清空
警報(ht.Count);
}