This website collects cookies to deliver better user experience
Set and Map, do you know them both?
Set and Map, do you know them both?
Introduction
When you think of data types in Javascript, I sure you can think of Number, String, Boolean, Object, etc.., Yes the above
are two major data types in javascript. in addition, there are many other built-in objects in javascript. there objects are not commonly used, but they are useless, let's look at them together!
Set
Basic introduction
Set is actually very smilar to array, and is also an ordered reference object. the main difference with an array is the
value within a set can't be duplicated, while an Array has no such limitation.
// get length of setmySet.size();// add value to the setmySet.add(3);// delete value of setmySet.delete(3);// Iterate Setfor(let items of mySet){console.log(items);}
How to use
Since set has the unique characteristic of internal values, it's perfect for de-duplication.
A map is very similar to object in that they are both key-value pairs.
the main differences are
The values inside the Map are ordered (consistent with the order when inserted);
The value type of the map is not limited and can be of any types (includes: function, objects, etc.. )
Commonly used API
let myMap =newMap();let array =[1,2];myMap.set(array,2);// get the lenght of mapmyMap.size;// add values to mapmyMap.set("google","duckduckgo");// delete value from mapmyMap.delete("google");// return true if successful, false// Get the value of a key in MapmyMap.get("duckduckgo");// Iterate through the Mapfor(let item of myMap){console.log(item);}console.log(myMap);// output Map(1) {Array(2) => 2}
It is extremely important that the values within a Map are ordered, so if there is a need to ensure that the order of traversal is consistent when traversing Objects, then a Map can be used.