


Detailed 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.
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



When using complex data structures in Java, Comparator is used to provide a flexible comparison mechanism. Specific steps include: defining the comparator class, rewriting the compare method to define the comparison logic. Create a comparator instance. Use the Collections.sort method, passing in the collection and comparator instances.

Data structures and algorithms are the basis of Java development. This article deeply explores the key data structures (such as arrays, linked lists, trees, etc.) and algorithms (such as sorting, search, graph algorithms, etc.) in Java. These structures are illustrated through practical examples, including using arrays to store scores, linked lists to manage shopping lists, stacks to implement recursion, queues to synchronize threads, and trees and hash tables for fast search and authentication. Understanding these concepts allows you to write efficient and maintainable Java code.

Reference types are a special data type in the Go language. Their values do not directly store the data itself, but the address of the stored data. In the Go language, reference types include slices, maps, channels, and pointers. A deep understanding of reference types is crucial to understanding the memory management and data transfer methods of the Go language. This article will combine specific code examples to introduce the characteristics and usage of reference types in Go language. 1. Slices Slices are one of the most commonly used reference types in the Go language.

AVL tree is a balanced binary search tree that ensures fast and efficient data operations. To achieve balance, it performs left- and right-turn operations, adjusting subtrees that violate balance. AVL trees utilize height balancing to ensure that the height of the tree is always small relative to the number of nodes, thereby achieving logarithmic time complexity (O(logn)) search operations and maintaining the efficiency of the data structure even on large data sets.

Overview of Java Collection Framework The Java collection framework is an important part of the Java programming language. It provides a series of container class libraries that can store and manage data. These container class libraries have different data structures to meet the data storage and processing needs in different scenarios. The advantage of the collection framework is that it provides a unified interface, allowing developers to operate different container class libraries in the same way, thereby reducing the difficulty of development. Data structures of the Java collection framework The Java collection framework contains a variety of data structures, each of which has its own unique characteristics and applicable scenarios. The following are several common Java collection framework data structures: 1. List: List is an ordered collection that allows elements to be repeated. Li

Introduction to JS-Torch JS-Torch is a deep learning JavaScript library whose syntax is very similar to PyTorch. It contains a fully functional tensor object (can be used with tracked gradients), deep learning layers and functions, and an automatic differentiation engine. JS-Torch is suitable for deep learning research in JavaScript and provides many convenient tools and functions to accelerate deep learning development. Image PyTorch is an open source deep learning framework developed and maintained by Meta's research team. It provides a rich set of tools and libraries for building and training neural network models. PyTorch is designed to be simple, flexible and easy to use, and its dynamic computation graph features make

Go and Node.js have differences in typing (strong/weak), concurrency (goroutine/event loop), and garbage collection (automatic/manual). Go has high throughput and low latency, and is suitable for high-load backends; Node.js is good at asynchronous I/O and is suitable for high concurrency and short requests. Practical cases of the two include Kubernetes (Go), database connection (Node.js), and web applications (Go/Node.js). The final choice depends on application needs, team skills, and personal preference.

Overview of the PHPSPL Data Structure Library The PHPSPL (Standard PHP Library) data structure library contains a set of classes and interfaces for storing and manipulating various data structures. These data structures include arrays, linked lists, stacks, queues, and sets, each of which provides a specific set of methods and properties for manipulating data. Arrays In PHP, an array is an ordered collection that stores a sequence of elements. The SPL array class provides enhanced functions for native PHP arrays, including sorting, filtering, and mapping. Here is an example of using the SPL array class: useSplArrayObject;$array=newArrayObject(["foo","bar","baz"]);$array
