search
HomeWeb Front-endJS Tutorialwhat is javascript hash

what is javascript hash

Nov 19, 2021 pm 04:20 PM
hashjavascript

In JavaScript, hash refers to a hash table, which is a data structure that directly accesses the memory storage location based on keywords; through the hash table, the storage location of the data element and the keyword of the data element are A certain correspondence is established between them, and the function that establishes this correspondence is called a hash function.

what is javascript hash

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

The basic concept of javascript hash:

Hash table (hash table) is a kind of data that directly accesses memory storage locations based on keywords Structure, through the hash table, a certain correspondence is established between the storage location of the data element and the key of the data element. The function that establishes this correspondence is called a hash function.
what is javascript hash
Hash table construction method:

Assume that the number of data elements to be stored is n, set a continuous storage unit with a length of m (m > n), respectively Taking the keyword Ki (0

From a mathematical point of view, the hash function is actually a mapping of keywords to memory units, so we hope to use the hash function to make the Huaxi address calculated by the hash function as uniform as possible through the simplest operation possible. Back mapping to a series of memory units, there are three key points in constructing a hash function: (1) The operation process should be as simple and efficient as possible to improve the insertion and retrieval efficiency of the hash table; (2) The hash function should have good Hash type to reduce the probability of hash collision; third, the hash function should have greater compression to save memory.

Commonly used methods:

  • Direct address method: Use a certain linear function value of the keyword as the hash address, which can be expressed as hash(K)=aK C; The advantage is that it does not Conflicts will occur, and the disadvantage is that the space complexity may be higher, which is suitable for cases with fewer elements.
  • Division with remainder method: It divides the data element keyword by a certain constant and the remainder is the hash address. This method is simple to calculate and has a wide range of applications. It is a frequently used hash function. , can be expressed as:
    hash(K=K mod C; The key to this method is the selection of constants. The general requirement is that it is close to or equal to the length of the hash table itself. Research theory shows that the constant works best when selecting prime numbers.
  • Number analysis method: This method is to take some uniform numbers in the data element keywords as the hash address. This can avoid conflicts as much as possible, but this method is only suitable for all keywords. The known situation is not applicable to those who want to design a more general hash table.
  • Square summation method: convert the current string into a Unicode value, and find the square of this value, and then square it The number of digits in the middle of the value is the hash value of the current number. The specific number depends on the size of the current hash table.
  • Segmented summation method: According to the number of digits in the current hash table, insert the Divide the value into several segments, add the segments, discard the highest bit, and the result is the hash value of this value.

Solution to hash conflict:

In the construction When using a hash table, there is a problem: for two different keywords, when calculating the hash address through our hash function, we get the same hash address. We call this phenomenon a hash conflict.

what is javascript hash

Hash conflict is mainly related to two factors

(1) Filling factor, the filling factor refers to what has been stored in the hash table The ratio of the number of data elements entered to the size of the hash address space, a=n/m; the smaller a, the smaller the possibility of conflict, on the contrary, the possibility of conflict is greater; but the smaller a, the better the space utilization The smaller, the larger a, the higher the space utilization. In order to take into account hash conflict and storage space utilization, a is usually controlled between 0.6-0.9, while HashTable in .net directly defines the maximum value of a. is 0.72 (Although Microsoft's official MSDN states that the default filling factor of HashTable is 1.0, it is actually a multiple of 0.72)
(2) It is related to the hash function used. If the hash function is appropriate, the hash function can be made Hash addresses are distributed as evenly as possible in the hash address space, thereby reducing the occurrence of conflicts, but the acquisition of a good hash function largely depends on a lot of practice.

1) Open addressing Method

Hi=(H(key) di) MOD m i=1,2,…k(k Where H(key) is the hash function; m is the hash Table length; di is an incremental sequence. There are 3 incremental sequences:
①Linear detection and then hashing: di=1,2,3,…,m-1
②Secondary detection and then hashing: di=12,- 12,22,-22,…±k^2(k ③Pseudo-random detection and then hashing: di=pseudo-random number sequence

shortcoming:

We can see a phenomenon: when records are already filled in at positions i, i 1, and i 2 in the table, the next records with hash addresses of i, i 1, i 2, and i 3 will be filled in. The position of i 3. This phenomenon of two records with different first hash addresses competing for the same subsequent hash address during the process of handling conflicts is called "secondary aggregation", that is, in the process of handling conflicts of synonyms Added non-synonymous conflicts. But on the other hand, using linear detection and then hashing to handle conflicts can guarantee that as long as the hash table is not full, an address Hk that does not conflict can always be found. Secondary detection and rehashing is only possible when the hash table length m is a prime number of the form 4j 3 (j is an integer). That is, the open addressing method will cause secondary aggregation, which is detrimental to search.

what is javascript hash
2) Rehash method

Hi = RHi (key), i=1,2,…k RHi are all different hash functions, that is, When a synonym produces an address conflict, another hash function address is calculated until no conflict occurs. This method is less prone to aggregation, but increases calculation time.

Disadvantages: Increased calculation time.

3) Chain address method (zipper method)

Store all records whose keywords are synonyms in the same linear linked list.

Advantages:

①The zipper method is simple to handle conflicts and there is no accumulation phenomenon, that is, non-synonymous words will never conflict, so the average search length is shorter;
②Because the zipper method The node space on each linked list is dynamically applied, so it is more suitable for situations where the table length cannot be determined before creating the table;
③ In order to reduce conflicts, the open addressing method requires the filling factor α to be small, so when the node size When larger, a lot of space is wasted. In the zipper method, α ≥ 1 is acceptable, and when the node is large, the pointer domain added in the zipper method can be ignored, thus saving space;
④ In the hash table constructed with the zipper method, the operation of deleting nodes Easy to implement. Just simply delete the corresponding node on the linked list. For the hash table constructed by the open address method, deleting a node cannot simply leave the space of the deleted node empty, otherwise the search path of the synonym node that is filled in the hash table after it will be truncated. This is because in various open address methods, empty address units (ie open addresses) are conditions for search failure. Therefore, when performing a deletion operation on a hash table that uses the open address method to handle conflicts, it can only mark the deleted node for deletion, but cannot actually delete the node.

Disadvantages:

The disadvantage of the zipper method is that pointers require additional space. Therefore, when the node size is small, the open addressing method is more space-saving, and if the saved pointer space is used Increasing the size of the hash table can make the fill factor smaller, which in turn reduces conflicts in the open addressing method and thus increases the average search speed.

what is javascript hash

#4) Establish a public overflow area

Assuming that the value range of the hash function is [0,m-1], then let the vector HashTable[0...m-1] is the basic table, each component stores a record, and the vector OverTable[0...v] is set up as the overflow table. All records whose keywords are synonymous with the keywords in the basic table, regardless of their hash addresses obtained by the hash function, will be filled in the overflow table in the event of a conflict.

A hash table implementation of a simple hash function without conflict handling

class Hash {
  constructor() {
    this.table = new Array(1024);
  }
  hash(data) {
    //就将字符串中的每个字符的ASCLL码值相加起来,再对数组的长度取余
    var total = 0;
    for (var i = 0; i < data.length; i++) {
      total += data.charCodeAt(i);
    }
    console.log("Hash Value: " + data + " -> " + total);
    return total % this.table.length;
  }
  insert(key, val) {
    var pos = this.hash(key);
    this.table[pos] = val;
  }
  get(key) {
    var pos = this.hash(key);
    return this.table[pos]
  }
  show() {
    for (var i = 0; i < this.table.length; i++) {
      if (this.table[i] != undefined) {
        console.log(i + ":" + this.table[i]);
      }
    }
  }
}
var someNames = ["David", "Jennifer", "Donnie", "Raymond", "Cynthia", "Mike", "Clayton", "Danny", "Jonathan"];
var hash = new Hash();
for (var i = 0; i < someNames.length; ++i) {
  hash.insert(someNames[i], someNames[i]);
}

hash.show();

what is javascript hash
uses the square middle method to construct the hash function and the open address method for linear detection method to resolve conflicts.

class Hash {
  constructor() {
    this.table = new Array(1000);
  }
  hash(data) {
    var total = 0;
    for (var i = 0; i < data.length; i++) {
      total += data.charCodeAt(i);
    }
    //把字符串转化为字符用来求和之后进行平方运算
    var s = total * total + ""
    //保留中间2位
    var index = s.charAt(s.length / 2 - 1) * 10 + s.charAt(s.length / 2) * 1
    console.log("Hash Value: " + data + " -> " + index);
    return index;
  }
  solveClash(index, value) {
    var table = this.table
    //进行线性开放地址法解决冲突
    for (var i = 0; index + i < 1000; i++) {
      if (table[index + i] == null) {
        table[index + i] = value;
        break;
      }
    }
  }
  insert(key, val) {
    var index = this.hash(key);
    //把取中当做哈希表中索引
    if (this.table[index] == null) {
      this.table[index] = val;
    } else {
      this.solveClash(index, val);
    }
  }
  get(key) {
    var pos = this.hash(key);
    return this.table[pos]
  }
  show() {
    for (var i = 0; i < this.table.length; i++) {
      if (this.table[i] != undefined) {
        console.log(i + ":" + this.table[i]);
      }
    }
  }
}
var someNames = ["David", "Jennifer", "Donnie", "Raymond", "Cynthia", "Mike", "Clayton", "Danny", "Jonathan"];
var hash = new Hash();
for (var i = 0; i < someNames.length; ++i) {
  hash.insert(someNames[i], someNames[i]);
}

hash.show();

what is javascript hash

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of what is javascript hash. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
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

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools