Copy Code code as follows:
function Hashtable ()//Custom 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++;}
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];}
}
Copy Code code as follows:
JS Hash Table
function HashTable () {
This. Objarr = {};
This. Count = 0;
Add to
This. ADD = function (key, value) {
if (this. Objarr.hasownproperty (key)) {
return false; If the key already exists, do not add
}
else {
This. Objarr[key] = value;
This. count++;
return true;
}
}
Whether to include an item
This. Contains = function (key) {
return this. Objarr.hasownproperty (key);
}
//Taking an item is actually equivalent to 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)); Script error
//return;
}
}
Removed from
This. Remove = function (key) {
if (this. Contains (key)) {
Delete this. Objarr[key];
This. count--;
}
}
Empty
This. Clear = function () {
This. Objarr = {}; This. Count = 0;
}
}
Test code:
Employees
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); is actually equivalent to HT. Objarr[i].username
Alert (HT. Objarr[i].username);
}
Ht. Remove (1);
Alert (HT. Contains (1)); False
Alert (HT. Contains (2)); True
Alert (HT. GetValue (1)); Abnormal
var result = ht. GetValue (2);
if (result!= null) {
Alert ("Employee Id: + result.id +"; UserName: "+ result.username);
}
Ht. ADD (2, "This key already exists!"); Add is not valid
Ht. Clear (); Empty
Alert (HT. Count);
}