What is the usage and difference between Map and Set in js
Today Xiaobian to share with you the js Map and Set usage and what is the difference between the relevant knowledge points, detailed content, clear logic, I believe most people still know too much about this knowledge, so share this article for everyone to refer to, I hope you have read this article after harvest, let's learn about it together.
First of all, let's look at Map.
Map is a structure of key-value pairs, similar to JSON objects.
(1)Map data structure is as follows
And what we can see here is that the data structure of Map is a structure of key-value pairs.
(2)Key can be not only a string but also an object.
var obj ={name:"Xiaoru",age:9}let map = new Map()map.set(obj,"111")
The printed results are as follows
(3)Map common syntax is as follows
//Initialize `Map` requires a two-dimensional array (see Map data structure), or directly initialize an empty `Map` let map = new Map();//Add key and value map.set ('Amy ',' female') map.set ('liuQi ',' male')//If there is a key, return true, otherwise it is falsemap.has ('Amy ') //truemap.has ('amy') //false//Obtain valuemap.get ('Amy ') //female'/Delete('Amy')map.get ('Amy') //undefined Delete successfully
(4)A key can only correspond to a value, multiple times for a key into the value, the value will overwrite the previous value
var map =new Mapmap.set('Amy',"female")map.set('Amy',"male")console.log(map)
The printed results are as follows
Learn more about Set.
Set objects are similar to arrays, and the values of the members are unique.
(1)The printed data structure is as follows
And this is printed out as an object.
(2)Most commonly used for deduplication, there are many ways to de-duplicate but none run as fast as it.
var arr=[1,3,4,2,5,1,4]//Here is an object converted into an array using es6 syntax, that is, the duplicate elements have been filtered out before converting the array var arr2=[... new Set(arr)] //[1,3,4,2,5]
(3)Set common syntax is as follows
//Initialize a Set, need an Array array, or empty Setvar set = new Set ([1,2,3,5,6]) console.log(set) // {1, 2, 3, 5, 6}//adds an element to Set.add(7) //{1, 2, 3, 5, 6, 7}//deletes an element from Set.delete(3) // {1, 2, 5, 6, 7}//checks if it contains this element, if true, falseset.has(2) //true Summarize the difference between Map and Set
(1)These two methods have extremely fast lookup speeds; so let's compare the execution times of Map, Set, Array
//initialize data var lng=100var arr =new Array(lng).fill(2)var set =new Set(arr)let map =new Map()for(var i=0;i