Copy codeThe Code is as follows:
Function Hashtable () // customize 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] ;}}
}
Copy codeThe Code is as follows:
// Js hash table
Function HashTable (){
This. ObjArr = {};
This. Count = 0;
// Add
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 it contains an item
This. Contains = function (key ){
Return this. ObjArr. hasOwnProperty (key );
}
// Retrieving an item is 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;
}
}
// Remove
This. Remove = function (key ){
If (this. Contains (key )){
Delete this. ObjArr [key];
This. Count --;
}
}
// Clear
This. Clear = function (){
This. ObjArr ={}; this. Count = 0;
}
}
Test code:
// Employee
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); // 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); // exception
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 invalid
// Ht. Clear (); // Clear
Alert (ht. Count );
}