A description of JavaScript hash table
JavaScript is not a hash table, has been in the java,c# sometimes used in this kind of data structure, JavaScript if not, feel very uncomfortable. In a thin look, the properties of the JavaScript object are actually very similar to the hash table.
Such as:
var person = {};
person["name"] = "Guan Yu";
We only need to encapsulate some hashtable functions on the basis of which we can get a compact hash table.
The Add function is as follows:
Add item
function name |
description |
return value |
add (key,value) |
|
based on key value |
object |
remove (key) |
|
no |
containskey (key) |
|
bool |
contai Nsvalue (value) |
|
bool |
tr>
getvalues () |
|
array |
getkeys () |
array |
getsize () |
Second, code implementation
Its specific implementation can see the code, are not very complex things.
function HashTable () {var size = 0;
var entry = new Object ();
This.add = function (key, value) {if (!this.containskey (key)) {size++;
} Entry[key] = value;
} This.getvalue = function (key) {return This.containskey (key) Entry[key]: null;
} This.remove = function (key) {if (This.containskey (key) && (delete entry[key))) {size--;
} This.containskey = function (key) {return (key in entry);
} This.containsvalue = function (value) {for (Var Prop. Entry) {if (entry[prop] = = value) {return true;
return false;
} this.getvalues = function () {var values = new Array ();
For (Var prop in entry) {Values.push (Entry[prop]);
return values;
} This.getkeys = function () {var keys = new Array ();
For (Var prop in entry) {Keys.push (prop);
return keys;
} this.getsize = function () {return size;
} this.clear = function () {size = 0;
Entry = new Object (); }
}
Simple Use Example:
var manht = new HashTable ();
Manht.add ("P1", "Liu Bei");
Manht.add ("P2", "Guan Yu");
$ ("#div1"). Text (Manht.getvalue ("P1"));
The above is the entire content of this article, I hope to help you!