This time I will show you how to use JS to implement a hash table, and what are the precautions for using JS to implement a hash table. The following is a practical case, let's take a look.
In algorithms, especially in algorithms related to arrays, the use of hash tables can solve problems very well, so this article will record some information about JS implementation of hash tables and give solutions to practical problems. example.Note: What this article writes is not a real hash table, but is similar to the use of hash tables.
Part 1: Related knowledge points
Enumeration of attributes:
var person = { name: "zzw", sex: "Male", age: 21 }; for (var prop in person) { console.log(prop + " ",person[prop]); }Output:
Deletion of attributes:
var person = { name: "zzw", sex: "Male", age: 21 }; var ifRemove = delete person.name; for (var prop in person) { console.log(prop + " ",person[prop]); } console.log(ifRemove);The attributes of the object can be deleted through delete, and there will be a return value. As follows:
var x = 1; console.log(delete x);At this time, the print station outputs false , because variables cannot be deleted. Detect whether the attribute exists:
var person = { name: "zzw", sex: "Male", age: 21 }; console.log("age" in person); console.log("someOther" in person);The former returns true and the latter returns false. That is, we can use in to determine whether an object contains this attribute.
Adding attributes:
var person = { name: "zzw", sex: "Male", age: 21 }; person["school"] = "XJTU"; console.log(person);The addition of attributes is very simple. As shown above, the final printed object contains the school attribute.
Part 2: Using js to implement a hash table
The following is a hash table obtained through the// 创建构造函数HashTable function HashTable() { // 初始化哈希表的记录条数size var size = 0; // 创建对象用于接受键值对 var res = {}; // 添加关键字,无返回值 this.add = function (key, value) { //判断哈希表中是否存在key,若不存在,则size加1,且赋值 if (!this.containKey(key)) { size++; } // 如果之前不存在,赋值; 如果之前存在,覆盖。 res[key] = value; }; // 删除关键字, 如果哈希表中包含key,并且delete返回true则删除,并使得size减1 this.remove = function (key) { if (this.containKey(key) && (delete res[key])) { size--; } }; // 哈希表中是否包含key,返回一个布尔值 this.containKey = function (key) { return (key in res); }; // 哈希表中是否包含value,返回一个布尔值 this.containValue = function (value) { // 遍历对象中的属性值,判断是否和给定value相等 for (var prop in res) { if (res[prop] === value) { return true; } } return false; }; // 根据键获取value,如果不存在就返回null this.getValue = function (key) { return this.containKey(key) ? res[key] : null; }; // 获取哈希表中的所有value, 返回一个数组 this.getAllValues = function () { var values = []; for (var prop in res) { values.push(res[prop]); } return values; }; // 根据值获取哈希表中的key,如果不存在就返回null this.getKey = function (value) { for (var prop in res) { if (res[prop] === value) { return prop; } } // 遍历结束没有return,就返回null return null; }; // 获取哈希表中所有的key,返回一个数组 this.getAllKeys = function () { var keys = []; for (var prop in res) { keys.push(prop); } return keys; }; // 获取哈希表中记录的条数,返回一个数值 this.getSize = function () { return size; }; // 清空哈希表,无返回值 this.clear = function () { size = 0; res = {}; }; }
Part 3: Application Example
Problem: Given an integer array (unordered), find two of them numbers such that their sum is a specified value, and returns the subscripts of the two numbers (array subscripts start from 0), assuming that the values of the array elements are different. The implementation is as follows:nbsp;html> <meta> <title>哈希表的使用</title> <script> function queryIndex(arr, result) { var hashTable = new HashTable(); var arrLength = arr.length; var sub = []; for (var i = 0; i < arrLength; i++) { // 扫描一遍,存储下标和值 hashTable.add(i, arr[i]); } for (var j = 0; j < arrLength; j++) { if (hashTable.containValue(result - arr[j]) && result !== 2*arr[j]) { // 获取两个下标,跳出循环 sub.push(j); var antherIndex = Number(hashTable.getKey(result - arr[j])); sub.push(antherIndex); break; } } if (sub.length !== 0) { return sub; } else { return -1; } } console.log(queryIndex([1,5,7,3,8], 15)); // 2, 4 console.log(queryIndex([8,18,28,12,29,17], 46)); // 2, 4 console.log(queryIndex([8,18,28,12,29,17], 2)); // -1 // 创建构造函数HashTable function HashTable() { // 初始化哈希表的记录条数size var size = 0; // 创建对象用于接受键值对 var res = {}; // 添加关键字,无返回值 this.add = function (key, value) { //判断哈希表中是否存在key,若不存在,则size加1,且赋值 if (!this.containKey(key)) { size++; } // 如果之前不存在,赋值; 如果之前存在,覆盖。 res[key] = value; }; // 删除关键字, 如果哈希表中包含key,并且delete返回true则删除,并使得size减1 this.remove = function (key) { if (this.containKey(key) && (delete res[key])) { size--; } }; // 哈希表中是否包含key,返回一个布尔值 this.containKey = function (key) { return (key in res); }; // 哈希表中是否包含value,返回一个布尔值 this.containValue = function (value) { // 遍历对象中的属性值,判断是否和给定value相等 for (var prop in res) { if (res[prop] === value) { return true; } } return false; }; // 根据键获取value,如果不存在就返回null this.getValue = function (key) { return this.containKey(key) ? res[key] : null; }; // 获取哈希表中的所有value, 返回一个数组 this.getAllValues = function () { var values = []; for (var prop in res) { values.push(res[prop]); } return values; }; // 根据值获取哈希表中的key,如果不存在就返回null this.getKey = function (value) { for (var prop in res) { if (res[prop] === value) { return prop; } } // 遍历结束没有return,就返回null return null; }; // 获取哈希表中所有的key,返回一个数组 this.getAllKeys = function () { var keys = []; for (var prop in res) { keys.push(prop); } return keys; }; // 获取哈希表中记录的条数,返回一个数值 this.getSize = function () { return size; }; // 清空哈希表,无返回值 this.clear = function () { size = 0; res = {}; }; } </script>I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:
How to use JS to implement the Baidu search box
How to internationalize your js code
The above is the detailed content of How to use JS to implement a hash table. For more information, please follow other related articles on the PHP Chinese website!

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.


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

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

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