Table of Contents
1. Dictionary class
2. Add a sorting function to the dictionary class
Home Web Front-end JS Tutorial Detailed explanation of JavaScript data structure dictionary class

Detailed explanation of JavaScript data structure dictionary class

Apr 09, 2018 am 11:29 AM
javascript data structure

A dictionary is a data structure that stores data in the form of "key-value" pairs. Like names and numbers in a phone book. JavaScript's Object class is designed in the form of a dictionary.

1. Dictionary class

Dictionary class (Dictionary) is based on Object. In the book "Data Structure and Algorithm JavaScript Description", the "dictionary" uses array to store data, which not only makes it difficult for readers to understand, but also does not achieve convenience. On the contrary, the code logic is wrong. The results cannot be output correctly as designed! ! !

/**
 * 构造函数
 * 基于对象存储数据
 * @constructor
 */function Dictionary(){
    this.datastore = new Object();
}
Dictionary.prototype = {    /* 修正constructor */
    constructor: Dictionary,    /* 统计个数 */
    size: function(){
        return Object.keys(this.datastore).length;
    },    /* 添加元素,给数组添加属性 */
    add: function(key, value){
        this.datastore[key] = value;
    },    /* 查找指定key的元素 */
    find: function(key){
        return this.datastore[key];
    },    /* 移除指定key的元素 */
    remove: function(key){
        delete this.datastore[key];
    },    /* 显示所有的键值对 */
    showAll: function(){
        for(var key in this.datastore){
            console.log(key + ": " + this.find(key));
        }
    }
};
Copy after login

Test:

var dic = new Dictionary();
dic.add("name", "ligang");
dic.add("age", 26);
dic.find("name");   // "ligang"dic.size();         // 2dic.showAll();      // "name: ligang" "age: 26"dic.remove("age");
dic.size();         // 1dic.showAll();      // "name: ligang"
Copy after login

Supplementary:Object.keys(obj)Returns an array containing all (self ) enumerable properties. Please check out - JavaScript objects and functions (JavaScript you don’t know)

2. Add a sorting function to the dictionary class

Sorting the dictionary can be converted into sorting by an object attribute. So we can use Object.keys()

/* 排序 */Dictionary.prototype.sort = function(){
    // 借助数组的默认排序
    var keys = Object.keys(this.datastore).sort();    
    // 新定义字典类
    var tempDic = new Dictionary();    
    for(var i = 0, len = keys.length; i < len; i++){        var key = keys[i];
        tempDic.add(key, this.find(key));
    }    
    return tempDic;
};
Copy after login

Test:

var dictionary = new Dictionary();
dictionary.add("b", 2);
dictionary.add("a", 1);
dictionary.add("c", 3);
dictionary.showAll();   // "b: 2" "a: 1" "c: 3"dictionary.sort().showAll();    // "a: 2" "b: 1" "c: 3"
Copy after login

Summary: The above dictionary class is not allowed Duplicate keys appear. For the same key, the later one will overwrite the previous one. Of course, other ways can be achieved by modifying the code.

Related recommendations:

Dictionary type

Javascript dictionary operation

JS array, dictionary

The above is the detailed content of Detailed explanation of JavaScript data structure dictionary class. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Compare complex data structures using Java function comparison Compare complex data structures using Java function comparison Apr 19, 2024 pm 10:24 PM

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.

Java data structures and algorithms: in-depth explanation Java data structures and algorithms: in-depth explanation May 08, 2024 pm 10:12 PM

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.

In-depth understanding of reference types in Go language In-depth understanding of reference types in Go language Feb 21, 2024 pm 11:36 PM

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.

PHP data structure: The balance of AVL trees, maintaining an efficient and orderly data structure PHP data structure: The balance of AVL trees, maintaining an efficient and orderly data structure Jun 03, 2024 am 09:58 AM

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.

Full analysis of Java collection framework: dissecting data structure and revealing the secret of efficient storage Full analysis of Java collection framework: dissecting data structure and revealing the secret of efficient storage Feb 23, 2024 am 10:49 AM

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

Hash table-based data structure optimizes PHP array intersection and union calculations Hash table-based data structure optimizes PHP array intersection and union calculations May 02, 2024 pm 12:06 PM

The hash table can be used to optimize PHP array intersection and union calculations, reducing the time complexity from O(n*m) to O(n+m). The specific steps are as follows: Use a hash table to map the elements of the first array to a Boolean value to quickly find whether the element in the second array exists and improve the efficiency of intersection calculation. Use a hash table to mark the elements of the first array as existing, and then add the elements of the second array one by one, ignoring existing elements to improve the efficiency of union calculations.

PHP SPL data structures: Inject speed and flexibility into your projects PHP SPL data structures: Inject speed and flexibility into your projects Feb 19, 2024 pm 11:00 PM

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

The application of Python dictionary in software development: creating a stable and reliable system The application of Python dictionary in software development: creating a stable and reliable system Feb 23, 2024 am 10:28 AM

1. Characteristics of Python dictionary A Python dictionary is an unordered collection of key-value pairs, represented by curly braces ({}). The keys of a dictionary can be any immutable type such as strings, numbers, or tuples, and the values ​​can be any type of data. Dictionary key-value pairs are separated by colons (:), and multiple key-value pairs are separated by commas (,). 2. Advantages of Python dictionary 1. Fast search: The dictionary uses a hash table to store data, and the search efficiency is extremely high, with an average search time of O(1). 2. Flexibility: Dictionaries can store different types of data, which makes them very flexible and adaptable to various application scenarios. 3. Scalability: The dictionary can dynamically add or delete key-value pairs, which is very suitable for processing data that needs to be updated frequently.

See all articles