search
HomeWeb Front-endFront-end Q&AIs there hashmap in javascript?

Is there hashmap in javascript?

Nov 18, 2021 am 11:13 AM
hashmapjavascript

There is hashmap in javascript, and the method to implement hashmap is "function HashMap(){this.map = {};}HashMap.prototype = {put : function...}".

Is there hashmap in javascript?

The operating environment of this article: windows7 system, javascript version 1.8.5, DELL G3 computer

Is there hashmap in javascript?

Implementation of HashMap in JavaScript

What is HashMap?

Implementation of Map interface based on hash table. This implementation provides all optional mapping operations and allows null values ​​and null keys. (The HashMap class is much the same as a Hashtable, except that it is not synchronized and allows null.) This class does not guarantee the order of the map, and in particular it does not guarantee that the order is immutable. This implementation provides stable performance for basic operations (get and put), assuming that the hash function distributes elements appropriately across buckets. The time required to iterate over a collection view is proportional to the "capacity" (number of buckets) of the HashMap instance and its size (number of key-value mappings).
So, if iteration performance is important, don't set the initial capacity too high (or the loading factor too low).

Implementation of HashMap in JavaScript
    var emojMap = ["[笑脸]", "[微笑]", "[喜欢]", "[飞吻]", "[尖叫]"
        , "[大哭]", "[哭笑不得]", "[墨镜]", "[饿了]", "[发呆]",
        "[沉思]", "[不屑]", "[鬼脸]", "[得意]", "[发怒]",
        "[眨眼]", "[汗]", "[舒服]", "[糟糕]", "[张嘴]",
        "[口罩]", "[没有嘴]", "[恶魔]", "[睡觉]", "[困乏]",
        "[难受]", "[调皮]", "[倔强]", "[困惑]", "[天使]",
        "[不看]", "[不听]", "[不说]", "[祈祷]", "[剪刀手]",
        "[拳头]", "[楼上]", "[好的]", "[赞]", "[鄙视]",
        "[鼓掌]", "[星星]", "[心]", "[心碎]", "[满分]",
        "[钱袋]", "[便便]", "[鬼魂]", "[眼睛]", "[鼻子]",
        "[耳朵]", "[嘴巴]", "[舌头]", "[猪]", "[狗]",
        "[猴子]", "[小马]", "[熊猫]", "[熊]", "[外星人]"
    ];

This number assembles the Emoji recognition data agreed during our development process and sends it to the server side

eg: I am HelloWord![Smile]Format

We need to parse data in the format of "[XX]" to match the corresponding image

Common methods of HashMap

In view of the operation of HashMap, we need to encapsulate the common operation methods

    function HashMap(){
        this.map = {};
    }
    HashMap.prototype = {
        put : function(key , value){// 向Map中增加元素(key, value) 
            this.map[key] = value;
        },
        get : function(key){ //获取指定Key的元素值Value,失败返回Null 
            if(this.map.hasOwnProperty(key)){
                return this.map[key];
            }
            return null;
        },
        remove : function(key){ // 删除指定Key的元素,成功返回True,失败返回False
            if(this.map.hasOwnProperty(key)){
                return delete this.map[key];
            }
            return false;
        },
        removeAll : function(){  //清空HashMap所有元素
            this.map = {};
        },
        keySet : function(){ //获取Map中所有KEY的数组(Array) 
            var _keys = [];
            for(var i in this.map){
                _keys.push(i);
            }
            return _keys;
        }
    };
    HashMap.prototype.constructor = HashMap;

The above is the HashMap operation method we encapsulate.

Using HashMap to develop an Emoji expression library

At first I thought of several solutions, just like the emojiMap array, if the other party sends a message

eg: I am HelloWord! [Smile] Format

    var r = /\[(.+?)\]/g;
    var str = "[笑脸][喜欢]emoji表情";
    var txt,url,tpl;
    for (var i in str.match(r)) {
        tpl = "<img  alt="Is there hashmap in javascript?" >";
        str = str.replace(str.match(r)[i],tpl);
    }
    console.log(str);

My initial idea was to use split to divide it into an array, and then use replace to replace the corresponding picture. Later I found this solution to emoticon Problems will occur if you send too many and cannot be replaced.
And you need to specify the index position of the array subscript
Later I changed it to the following method:

    var hashMap = new HashMap();
    //先向hashMap中存入元素
    for(var i in emojMap){
        hashMap.put(emojMap[i] ,(parseInt(i))+'.png');
    }
    var r = /([^\[\]]+)(?=\])/g;
    var str = "[笑脸][喜欢]emoji表情";
    var txt,url,tpl;
    for (var i in str.match(r)) {
        //获取hashMap中对应的Value
        txt = hashMap.get(str.match(r)[i])
        tpl = "<img  alt="Is there hashmap in javascript?" >";
        str = str.split(m[i]).join(tpl);
    }
    str=str.replace(/\[|]/g,'');
    console.log(str);

The advantage of using HasMap is that there is no need Worry about the location of the key, because each key corresponds to a val.

In this way, it can be perfectly replaced with Emoji pictures for display.

Recommended study: "javascript basic tutorial"

The above is the detailed content of Is there hashmap in javascript?. 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
React vs. Backend Frameworks: A ComparisonReact vs. Backend Frameworks: A ComparisonApr 13, 2025 am 12:06 AM

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

HTML and React: The Relationship Between Markup and ComponentsHTML and React: The Relationship Between Markup and ComponentsApr 12, 2025 am 12:03 AM

The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

React and the Frontend: Building Interactive ExperiencesReact and the Frontend: Building Interactive ExperiencesApr 11, 2025 am 12:02 AM

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React and the Frontend Stack: The Tools and TechnologiesReact and the Frontend Stack: The Tools and TechnologiesApr 10, 2025 am 09:34 AM

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React's Role in HTML: Enhancing User ExperienceReact's Role in HTML: Enhancing User ExperienceApr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React Components: Creating Reusable Elements in HTMLReact Components: Creating Reusable Elements in HTMLApr 08, 2025 pm 05:53 PM

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.

React Strict Mode PurposeReact Strict Mode PurposeApr 02, 2025 pm 05:51 PM

React Strict Mode is a development tool that highlights potential issues in React applications by activating additional checks and warnings. It helps identify legacy code, unsafe lifecycles, and side effects, encouraging modern React practices.

React Fragments UsageReact Fragments UsageApr 02, 2025 pm 05:50 PM

React Fragments allow grouping children without extra DOM nodes, enhancing structure, performance, and accessibility. They support keys for efficient list rendering.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools