Example analysis of JS implementation hashtable (hash table) _javascript skills

Source: Internet
Author: User
Tags hash

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 tr>
function name description return value
add (key,value)
based on key value object
remove (key) no
containskey (key) bool
contai Nsvalue (value) bool
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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.