search
HomeWeb Front-endJS TutorialDetailed introduction to hash table (hash table) in JavaScript (code example)

This article brings you a detailed introduction (code example) about hash tables (hash tables) in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.

Hash table

Hash table (Hash table, also called hash table) directly accesses the memory storage location based on the key (Key) data structure. That is, it accesses the record by computing a function on the key value that maps the required query data to a location in the table, which speeds up the lookup. This mapping function is called a hash function, and the array storing the records is called a hash table.

Detailed introduction to hash table (hash table) in JavaScript (code example)

We start from the above picture to analyze

  • There is a set U, which are 1000, 10, 152, 9733, 1555, 997, 1168

  • The right side is a list (hash table) of 10 slots. We need to store the integers in the set U into this list

  • How to store it and in which slot? This problem needs to be solved through a hash function. My storage method is to take the remainder of 10. Let’s look at this picture

    • 1000 =0, 10 =0 Then the two integers 1000 and 10 will be It is stored in the slot numbered 0

    • 152 =2, then it is stored in the slot 2

    • 9733 =3 Stored in slot numbered 3

Through the above simple example, you should have a general understanding of the following points

  • The set U is the key that may appear in the hash table

  • The hash function is a method of your own design to convert the keys in the set U The value is stored in the hash table through some calculation, such as the remainder in the example

  • The hash table stores the calculated key

Then let’s see how we usually get the value?

For example, we store a key of 1000 and a value of 'Zhang San' ---> {key: 1000, value: 'Zhang San'}
From our above explanation, it Should it be stored in the slot of 1000?
When we want to find the value Zhang San through the key, can we just search in the key slot? At this point you can stop and think.

Some terms of hashing (you can take a brief look)

  • All the keys that may appear in the hash table are called the complete set U

  • Use M to represent the number of slots

  • Given a key, the hash function calculates which slot it should appear in. The hash function h=k% in the above example M, the hash function h is a mapping from key k to slot.

  • 1000 and 10 are both stored in the slot numbered 0. This situation is called a collision.

After reading this, I don’t know if you have a general understanding of what a hash function is. Through the example and your thinking, you can go back and read the definition of hash table at the top of the article. If you can read it, then I guess you should understand it.

Commonly used hash functions

Processing integers h=>k%M (that is, the example we gave above)

Processing strings:

    function h_str(str,M){
        return [...str].reduce((hash,c)=>{
            hash = (31*hash + c.charCodeAt(0)) % M
        },0)
    }

The hash algorithm is not the focus here, and I have not studied it in depth. The main thing here is to understand what kind of data structure a hash table is, what advantages it has, and what specifically it does.
The hash function just maps keys to lists through a certain algorithm.

Building a hash table

Through the above explanation, we will make a simple hash table here

The composition of the hash table

  • M slots

  • There is a hash function

  • There is an add method to add the key value to the hash table

  • There is a delete method to delete

  • There is a search method to find the corresponding value based on the key

Initialization

- Initialize how many slots the hash table has
- Use an array to create M slots

    class HashTable {
        constructor(num=1000){
            this.M = num;
            this.slots = new Array(num);
        }
    }

Hash function

Hash function for processing strings, Strings are used here because values ​​can also be transferred into strings, which is more general.

First convert the passed key value into a string. In order to be more rigorous,

convert the string is an array, for example 'abc' => [...'abc'] => ['a','b','c']

Calculate the charCodeAt of each character separately, The purpose of taking the remainder of M is to exactly correspond to the number of slots. You only have 10 slots in total, and your value will definitely fall into the slots of 0-9

    h(str){
        str = str + '';
        return [...str].reduce((hash,c)=>{
            hash = (331 * hash + c.charCodeAt()) % this.M;
            return hash;
        },0)
    }

Add

Call the hash function Get the corresponding storage address (which is the slot of our analogy)

Because there may be multiple values ​​stored in a slot, it needs to be represented by a two-dimensional array, such as the slot number we calculated is 0, which is slot[0], then we should store it in slot[0] [0]. If the slot that comes in later is also the slot numbered 0, then we should store it in slot[0] [1]

    add(key,value) {
        const h = this.h(key);
        // 判断这个槽是否是一个二维数组, 不是则创建二维数组
        if(!this.slots[h]){
            this.slots[h] = [];
        }
        // 将值添加到对应的槽中
        this.slots[h].push(value);
    }

Delete

Find the slot through hash algorithm

Delete through filtering

    delete(key){
        const h = this.h(key);
        this.slots[h] = this.slots[h].filter(item=>item.key!==key);
    }

Find

Find the corresponding slot through hash algorithm

Use the find function to find the value of the same key

Return the corresponding value

    search(key){
        const h = this.h(key);
        const list = this.slots[h];
        const data = list.find(x=> x.key === key);
        return data ? data.value : null;    
    }

总结

讲到这里,散列表的数据结构已经讲完了,其实我们每学一种数据结构或算法的时候,不是去照搬实现的代码,我们要学到的是思想,比如说散列表它究竟做了什么,它是一种存储方式,可以快速的通过键去查找到对应的值。那么我们会思考,如果我们设计的槽少了,在同一个槽里存放了大量的数据,那么这个散列表它的搜索速度肯定是会大打折扣的,这种情况又应该用什么方式去解决,又或者是否用其他的数据结构的代替它。

补充一个小知识点

v8引擎中的数组 arr = [1,2,3,4,5] 或 new Array(100) 我们都知道它是开辟了一块连续的空间去存储,而arr = [] , arr[100000] = 10 这样的操作它是使用的散列,因为这种操作如果连续开辟100万个空间去存储一个值,那么显然是在浪费空间。


The above is the detailed content of Detailed introduction to hash table (hash table) in JavaScript (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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 Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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.