Examples of implementing HashTable in js (hash table) I. Introduction to javascript hash table
There is no hash table in javascript, and this data structure is sometimes used in java and C #. If there is no hash table in javascript, it is very difficult. In detail, the property of javascript objects is actually very similar to that of hash tables.
For example:
Var person = {}; person ["name"] = "Guan Yu ";
We only need to encapsulate some HashTable functions on the basis to get a simplified hash table.
Add the following functions:
Ii. Code Implementation
Its specific implementation can be used to view the code, which is not very complicated.
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 in 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 Example:
Var manHT = new HashTable (); manHT. add ("p1", "Liu Bei"); manHT. add ("p2", "Guan Yu"); $ ("# p1 "). text (manHT. getValue ("p1 "));