Table of Contents
Dictionary (Map):
Summary**: **
Home Web Front-end Front-end Q&A What is the difference between es6 set and map

What is the difference between es6 set and map

Apr 15, 2022 pm 06:37 PM
es6 map set

Difference: 1. Set refers to the "set" structure, while Map refers to the "dictionary" structure; 2. Set stores elements in the form of "[value, value]", while Map stores elements in the form of "[value, value]" It is stored in the form of "[key, value]"; 3. Map can use get() to find a specific value by key and return it, but set cannot.

What is the difference between es6 set and map

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

Brief description:

  • The main application scenarios of Set and Map are data reorganization and data storage.
  • Set is a data structure called a set, and Map is a data structure called a dictionary.

The difference between sets and dictionaries:

  • Common points: Sets and dictionaries can store unique values ​​
  • Differences: Sets are represented by [value , value] to store elements, the dictionary is to store elements in the form of [key, value]

Set

ES6 new one A new data structure, similar to an array, but the members are unique and unordered, with no duplicate values.

Set itself is a constructor used to generate Set data structure.

Set objects allow you to store unique values ​​of any type, whether primitive values ​​or object references.

const s = new Set()
[1, 2, 3, 4, 3, 2, 1].forEach(x => s.add(x))
for (let i of s) {
    console.log(i)	// 1 2 3 4
}
// 去重数组的重复对象
let arr = [1, 2, 3, 2, 1, 1]
[... new Set(arr)]	// [1, 2, 3]
Copy after login

Note: When adding a value to Set, no type conversion occurs, so `5` and `"5"` are two different values. Set internally determines whether two values ​​are different. The algorithm used is called "Same-value-zero equality", which is similar to the **exact equality** operator (`===`). The main difference is **`NaN` is equal to itself, while the exact equality operator considers `NaN` not to be equal to itself. **

let set = new Set();
let a = NaN;
let b = NaN;
set.add(a);
set.add(b);
set // Set {NaN}

let set1 = new Set()
set1.add(5)
set1.add('5')
console.log([...set1])	// [5, "5"]
Copy after login

Operation method:

  • add(value): New, equivalent to push in array.

  • delete(value): Delete the value in the collection if it exists.

  • has(value): Determine whether value exists in the collection.

  • clear(): Clear the collection.

Traversal method: Traversal method (traversal order is insertion order)

  • keys(): Returns an iterator containing all keys in the collection .

  • values(): Returns an iterator containing all values ​​in the collection.

  • entries(): Returns a key-value iterator containing all elements in the Set object.

  • forEach(callbackFn, thisArg): Used to perform callbackFn operations on collection members. If the thisArg parameter is provided, this in the callback will be this parameter. There is no return value.

Dictionary (Map):

is a structure of a set of key-value pairs, with extremely fast search speed.

const m = new Map()
const o = {p: 'haha'}
m.set(o, 'content')
m.get(o)	// content

m.has(o)	// true
m.delete(o)	// true
m.has(o)	// false
Copy after login

Operation method:

  • set(key, value): Add new elements to the dictionary.
  • get(key): Find a specific value by key and return it.
  • has(key): Determine whether the key key exists in the dictionary.
  • delete(key): Remove the corresponding data from the dictionary through the key key.
  • clear(): Delete all elements in this dictionary.

Traversal method:

  • Keys(): Return all key names contained in the dictionary in the form of an iterator.
  • values(): Returns all the values ​​contained in the dictionary in the form of an iterator.
  • entries(): Returns an iterator of all members.
  • forEach(): Traverse all members of the dictionary.

Summary**: **

Set:

  • refers to the "set" structure

  • [value, value], the key value and the key name are consistent (or only the key value, no key name).

  • Cannot look up a specific value by key

Map:

  • ##Refers to a "dictionary" structure

  • [key, value], the key value and the key name are inconsistent


  • Map can use get() to find a specific value by key and return

【Related recommendations:

javascript video tutorial, web front-end

The above is the detailed content of What is the difference between es6 set and map. 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

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 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)

How does springboot read lists, arrays, map collections and objects in yml files? How does springboot read lists, arrays, map collections and objects in yml files? May 11, 2023 am 10:46 AM

application.yml defines the list collection. The first way is to use the @ConfigurationProperties annotation to obtain all the values ​​​​of the list collection type:code:status:-200-300-400-500. Write the entity class corresponding to the configuration file. What needs to be noted here is that defining the list Collection, first define a configuration class Bean, and then use the annotation @ConfigurationProperties annotation to obtain the list collection value. Here we will explain the role of the relevant annotations. @Component hands over the entity class to Spring management @ConfigurationPropertie

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

How to set expiration time map in Java How to set expiration time map in Java May 04, 2023 am 10:13 AM

1. Technical background In actual project development, we often use caching middleware (such as redis, MemCache, etc.) to help us improve the availability and robustness of the system. But in many cases, if the project is relatively simple, there is no need to specifically introduce middleware such as Redis to increase the complexity of the system in order to use caching. So does Java itself have any useful lightweight caching components? The answer is of course yes, and there is more than one way. Common solutions include: ExpiringMap, LoadingCache and HashMap-based packaging. 2. Technical effects to realize common functions of cache, such as outdated deletion strategy, hotspot data warm-up 3. ExpiringMap3.

Is async for es6 or es7? Is async for es6 or es7? Jan 29, 2023 pm 05:36 PM

async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.

What are the ways to implement thread safety for Map in Java? What are the ways to implement thread safety for Map in Java? Apr 19, 2023 pm 07:52 PM

Method 1. Use HashtableMapashtable=newHashtable(); This is the first thing everyone thinks of, so why is it thread-safe? Then take a look at its source code. We can see that our commonly used methods such as put, get, and containsKey are all synchronous, so it is thread-safe publicsynchronizedbooleancontainsKey(Objectkey){Entrytab[]=table;inthash=key.hashCode( );intindex=(hash&0x7FFFFFFF)%tab.leng

How to implement array deduplication in es5 and es6 How to implement array deduplication in es5 and es6 Jan 16, 2023 pm 05:09 PM

In es5, you can use the for statement and indexOf() function to achieve array deduplication. The syntax "for(i=0;i<array length;i++){a=newArr.indexOf(arr[i]);if(a== -1){...}}". In es6, you can use the spread operator, Array.from() and Set to remove duplication; you need to first convert the array into a Set object to remove duplication, and then use the spread operator or the Array.from() function to convert the Set object back to an array. Just group.

How to convert objects to Maps in Java - using BeanMap How to convert objects to Maps in Java - using BeanMap May 08, 2023 pm 03:49 PM

There are many ways to convert javabeans and maps, such as: 1. Convert beans to json through ObjectMapper, and then convert json to map. However, this method is complicated and inefficient. After testing, 10,000 beans were converted in a loop. , it takes 12 seconds! ! ! Not recommended. 2. Obtain the attributes and values ​​of the bean class through Java reflection, and then convert them into the key-value pairs corresponding to the map. This method is the second best, but it is a little more troublesome. 3. Through net.sf.cglib.beans.BeanMap Method in the class, this method is extremely efficient. The difference between it and the second method is that because of the use of cache, the bean needs to be initialized when it is first created.

Optimize the performance of Go language map Optimize the performance of Go language map Mar 23, 2024 pm 12:06 PM

Optimizing the performance of Go language map In Go language, map is a very commonly used data structure, used to store a collection of key-value pairs. However, map performance may suffer when processing large amounts of data. In order to improve the performance of map, we can take some optimization measures to reduce the time complexity of map operations, thereby improving the execution efficiency of the program. 1. Pre-allocate map capacity. When creating a map, we can reduce the number of map expansions and improve program performance by pre-allocating capacity. Generally, we

See all articles