Usage scenarios of set and map in JS

usage scenarios of set and map in JS

Jun.28,2022

< H1 > Set usage scenario < / H1 > The difference between

Set and Array is that every element in Set is unique, for example, you have a Array with 4 elements [1,2,3,1] , if you convert it to Set , it becomes [1,2,3] . So we can use this feature of Set to remove the weight of the integer array. Note, however, that if your array is [{name: 1}, {name: 1}] which contains Object , then you can't deduplicate it when you convert it to Set , because although the two objects look the same, in the view of Set , the two objects in this array are two completely different values, so they do not meet the de-duplication requirements.

< H1 > Map usage scenario < / H1 >

Map is similar to Object , but Map has a special application scenario. If you are unsure of the name of the key in the key-value pair during development, you need to use Map . For example, you need to dynamically get the key values from MongoDB and display them to the user, but maybe you don't care what the key names are, so in this case, you can use Map , for example:

var myMap = new Map();

var keyObj = {},
    keyFunc = function () { return 'hey'},
    keyString = "a string";

myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

console.log(myMap.get(keyFunc));
Menu