Implementation of HashTable (hash table) instance analysis in js

Source: Internet
Author: User
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 "));
Related Article

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.