JavaScript dictionaries and collections (summary sharing)

WBOY
Release: 2022-07-28 15:37:47
forward
2365 people have browsed it

This article brings you relevant knowledge aboutjavascript, mainly introducing the detailed explanation of JavaScript dictionaries and collections. A collection is composed of a group of unordered and non-repeating elements. We can think of a set as a special kind of array. Its special feature is that it is unordered and non-repeating, which means that we cannot access it through subscripts, and there will be no duplicate elements in the set.

JavaScript dictionaries and collections (summary sharing)

[Related recommendations:javascript video tutorial,web front-end]

Dictionary

What is a dictionary

When it comes to dictionaries, the first thing that comes to mind is the Xinhua Dictionary. In fact, it is similar to the dictionary in programming. Both There is a characteristic thatcorresponds toone-to-one (yi yi dui ying), ormaps.

Dictionaries are usually stored in **[key, value]** pairs. Because they are stored in the form of key-value pairs, it is more convenient to obtainvalue# throughkey

##For example, storing user information:

{ 'username': '一碗周', 'age': 18 }
Copy after login

Dictionary in JavaScript

In JavaScript, objects seem to have dictionaries All the features, but

Mapis added in ES6 to represent a dictionary. The map here is not translated into a map, but a mapping.

The sample code is as follows:

// 创建一个字典 const map = new Map() // 往字典中存储信息 map.set('username', '一碗周') map.set('age', 18) console.log(map) // Map(2) { 'username' => '一碗周', 'age' => 18 }
Copy after login

Application of Dictionary

When we were learning linked lists, we did an algorithm question, and we tried our best to get the correct question number. It is a question for 20. Its title is:

Valid brackets. The main idea of the question is to determine whether the brackets in the given string match. If they match,truewill be returned, otherwisefalse will be returned..

The problem-solving idea is as follows:

    Determine whether the length of the string is an even number. If it is not an even number, it will directly return
  • false, because of the parentheses They all appear in pairs;
  • Create a new stack;
  • Traverse the string, and when traversing each item, if it is a left bracket, push it onto the stack; if it is a right bracket, and Compare the top of the stack. If there is a match, pop the stack. If not, return
  • false.

Our original solution:

/** * @param {string} s * @return {boolean} */ var isValid = function(s) { if (s.length % 2 !== 0) return false const stack = [] for(let i = 0; i
        
Copy after login

In the above code, the judgment condition in the conditional judgment is very long, then we can use the dictionary To optimize this writing method, the

implementation code is as follows:

/** * @param {string} s * @return {boolean} */ var isValid = function(s) { // 1. 判断字符串的长度是否为偶数,不为偶数直接返回false,因为括号都是成对出现的; if (s.length % 2 !== 0) return false const stack = [] const map = new Map() // 将所有括号的对应关系存储在字典中 map.set('(', ')') map.set('[', ']') map.set('{', '}') for(let i = 0; i
        
Copy after login

In this code, we have optimized the judgment conditions in the

ifstatement.

Set

What is a set

A set is a set of

unordered and non-repeatingcomposed of elements. We can think of a set as a special array. Its special feature is that it isunordered and non-repeating, which means that we cannot access it through subscripts, and there will be no duplication in the set. Element;

Set in JS

provides the data structure of collection in JavaScript, that is,

Set,in MDN The description is as follows:

SetAn object is a collection of values, and you can iterate over its elements in the order of insertion. The elements in the Set will onlyappear once, that is, the elements in the Set are unique.

Operations in the collection

There are mainly the following scene operations in the collection:

    Add elements to the collection;
  • Delete an element in the set;
  • Judge whether the element is in the set;
  • Clear the set;
  • Find intersection, union, and difference set;
Except for the last

Setobject provides us with the corresponding method,The sample code is as follows:

const arr = [1, 2, 3, 2, 3, 4, 5] // 利用set实现去重 const set = new Set(arr) // [1, 2, 3, 4, 5] // 往集合中添加元素 set.add(3) // [1, 2, 3, 4, 5] 添加失败,集合中不允许出现重复元素 set.add(6) // [1, 2, 3, 4, 5, 6] // 判断元素是否在集合中 set.has(2) // true set.has(7) // false // 删除集合中的元素 set.delete(1) // [2, 3, 4, 5, 6] // 清空集合 set.clear()
Copy after login

Intersection and union , Encapsulation of difference sets

First we need to understand what intersection, union and difference set are.

  • Union:For the given two sets, return a new set containing all elements in both sets
  • Intersection:For the given two sets, return a new set containing the common elements in the two sets
  • Difference set:For the given two sets, return a new set containing all elements that exist A new set of elements that are in the first set and do not exist in the second set
The following figure better explains what intersection, union, and difference are.

The encapsulated code is as follows:

// 求两个集合的并集 export function union(setA, setB) { let _union = new Set(setA) for (let elem of setB) { _union.add(elem) // 因为集合中不存在重复元素 } return _union } // 求两个集合的交集 export function intersection(setA, setB) { let _intersection = new Set() for (let elem of setB) { if (setA.has(elem)) { _intersection.add(elem) } } return _intersection } // 求两个集合的差集 export function difference(setA, setB) { let _difference = new Set(setA) for (let elem of setB) { _difference.delete(elem) } return _difference }
Copy after login

The three encapsulated methods all take advantage of the feature that collections cannot be repeated.

【Related recommendations:

javascript video tutorial,web front-end

The above is the detailed content of JavaScript dictionaries and collections (summary sharing). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jb51.net
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!