Home > Article > Web Front-end > 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.
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.
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.
Through the above explanation, we will make a simple hash table here
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
- 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 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) }
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); }
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 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!