This article mainly introduces simple examples of simulating hashtable in js. If you need some help, please refer to it.
The Code is 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;} 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. the code for _ hash [k] ;}} 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 or not this is included. contains = function (key) {return this. objArr. h AsOwnProperty (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 invalid // ht. Clear (); // Clear alert (ht. Count );}