search
HomeWeb Front-endJS TutorialDetailed introduction to how JavaScript implements hash tables

This article brings you relevant knowledge about javascript, which mainly introduces related issues about how JavaScript implements hash tables, and encapsulates the entire structure of the array into which the final data is inserted. , what you get is the hash table, I hope it will be helpful to everyone.

Related recommendations: javascript learning tutorial

Hash tables are usually implemented based on arrays. But it has many advantages over arrays:

  1. It can provide very fast insert-deletion-find operations
  2. No matter how much data, insertion and deletion need to be close to constant time: that is, O(1) time level. In fact, it only takes a few machine instructions to do it.
  3. The hash table is faster than the tree, and you can basically find the desired element instantly
  4. The hash table is much easier to code than the tree

Some shortcomings of hash tables compared to arrays:

  1. The data in the hash table is not in order, so it cannot be traversed in a fixed way. The elements
  2. Normally, the keys in the hash table are not allowed to be repeated, and the same key cannot be placed. It is used to save different elements
  3. The space utilization is not high, and the bottom layer uses is an array, and some cells are not utilized

What is a hash table?

  • Hash tables are not easy to understand, unlike arrays, linked lists, and trees, which can express their structure and principles in the form of graphics.
  • The structure of the hash table is an array, but its magic lies in a transformation of the subscript value, which we can call Hash function, HashCode can be obtained through the hash function.

Some concepts of hash tables

  • Hashing: Convert large numbers The process of forming a subscript within the array range is called hashing;
  • Hash function: We usually use Word is converted into big number, and the code implementation of big number for hashing is placed in a function, which is called Hash function;
  • Hash table: Encapsulate the entire structure of the array inserted into the final data, and get is the hash table.

Problems that still need to be solved:

  • The hashed subscript is still possibleDuplicate, how to solve this What's the problem? This situation is called conflict. Conflict is inevitable, and we can onlysolve the conflict.

Methods to resolve conflicts

Two common solutions to resolve conflicts:

  • Option 1:Chain address Method(zipper method);

As shown in the figure below, we will perform the remainder operation on 10 for each number, then the remainder The range 0~9 is used as the subscript value of the array. Moreover, the position corresponding to each subscript value in the array no longer stores a number, but stores an array or linked list## composed of numbers that have the same remainder after a remainder operation. #.

Summary: The way to resolve conflicts with the chain address method is that the data stored in each array unit is no longer A single data , but a chain. The commonly used data structure for this chain is array or linked list. The search efficiency of the two data structures is equivalent (because the elements of the chain are generally Not too much).

    Option 2:
  • Open address method;
The main working method of the open address method is

Looking for blank cells To place conflicting data items.

According to the different ways of detecting the position of blank cells, it can be divided into three methods:

  • Linear detection
  • Secondary detection
  • Rehashing method
It can be seen that as the loading factor increases, the average The detection length increases linearly and gently. The chain address method is often used in development. For example, the HashMap in Java uses the

chain address method.

Excellent hash function

The advantage of a hash table is its speed, so the hash function cannot use complex algorithms that consume high performance. One way to improve speed is to

minimize multiplications and divisions in the hash function.

A high-performance hash function should have the following two advantages:

  • Fast calculation;
  • Uniform distribution;
Quick calculation

Horner's Law: In China, Horner's Law is also called Qin Jiushao's Algorithm. The specific algorithm is:

When finding the value of a polynomial, First, calculate the value of the linear polynomial in the innermost bracket, and then calculate the value of the linear polynomial layer by layer from the inside out. This algorithm converts the value of n degree polynomial f(x) into the value of n degree polynomials.

Before transformation:

  • Number of multiplications: n(n 1)/2 times;
  • Number of additions: n times;

After transformation:

  • Number of multiplications: n times;
  • Number of additions: n times;

If big O is used to represent the time complexity, it will directly drop from O(N2) before transformation to O(N).

Uniform distribution

In order to ensure that the data is evenly distributed in the hash table, when we need touse constants, try to use Prime numbers; For example: the length of the hash table, the base of Nth power, etc.

HashMap in Java uses the chain address method, and the hashing method uses the formula: index = HashCode (key) & (Length-1)

That is to say, the data is converted into binary for and operations instead of remainder operation. In this way, the computer directly operates on binary data, which is more efficient. However, JavaScript will have problems when performing and operations called big data, so the remainder operation will still be used when using JavaScript to implement hashing.

                    function HashTable() {
                // 存放相关的元素
                this.storage = [];
                // 存了多少数据
                this.count = 0;
                // 用于标记数组中一共存放了多少个元素
                this.limit = 7;
                /*
           设计哈希函数
           ①将字符串转成比较大的数字
           ②将大的数字hashCode压缩到数组范围之内
            */
                HashTable.prototype.hashFunction = function (str, size) {
                    var hashCode = 0;
                    //秦九韶算法(霍纳算法)
                    // 哈希表的长度、N次幂的底数等尽量选取质数
                    for (var i = 0; i  this.limit * 0.75) {
                        var newLimit = this.limit * 2;
                        var prime = this.getPrime(newLimit);
                        this.resize(prime);
                    }
                };
                // 获取
                HashTable.prototype.get = function (key) {
                    var index = this.hashFunction(key, this.limit);
                    var bucket = this.storage[index];
                    if (bucket == null) return null;
                    for (var i = 0; i  7 && this.count  0 ? false : true;
                };
                // size
                HashTable.prototype.size = function () {
                    return this.count;
                };
                // toString
                HashTable.prototype.toString = function () {
                    var str = '';
                    for (var i = 0; i <p><detailed introduction to how javascript implements hash tables src="https://Detailed%20introduction%20to%20how%20JavaScript%20implements%20hash%20tables.php.cn/upload/article/000/000/067/4ca10f86d3fe737c57c2ff0ae29c077f-3.png" alt="Detailed introduction to how JavaScript implements hash tables"></detailed></p><p>Related recommendations: <a href="https://www.php.cn/course/list/17.html" target="_blank">javascript learning tutorial</a><br></p>

The above is the detailed content of Detailed introduction to how JavaScript implements hash tables. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)