Home > Web Front-end > JS Tutorial > body text

Example analysis of js implementation of HashTable (hash table)

高洛峰
Release: 2016-12-06 11:03:23
Original
1024 people have browsed it

1. Introduction to javascript hash table

There is no hash table in javascript. This kind of data structure is sometimes used in java and C#. If there is no hash table in javascript, it feels very uncomfortable. If you look closely, you will find that the properties of JavaScript's object are actually very similar to hash tables.

Such as:

var person = {};
person["name"] = "关羽";
Copy after login

We only need to encapsulate some HashTable functions on top of it to get a simplified version of the hash table.

Add the function as follows:

Example analysis of js implementation of HashTable (hash table)

2. Code implementation

You can check the code for its specific implementation, it 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();
 }
}
Copy after login

Simple usage example:

var manHT = new HashTable();
manHT.add("p1","刘备");
manHT.add("p2","关羽");
$("#div1").text(manHT.getValue("p1"));
Copy after login


Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template