The preface
First, the Map is not a Map of array operations, and the Set is not a Set of values.
A Map is a collection of data items with keys, just like an Object. But the biggest difference is that maps allow any type of key. A Set is a special Set of types — a “Set of values” (without keys), each of which can occur only once.
Map
Map Basic Attributes
new Map()
Create a map.map.set(key, value)
Store values by key.map.get(key)
Returns the value based on the key, ifmap
There is no corresponding inkey
, the returnundefined
.map.has(key)
– ifkey
If it exists, returntrue
Otherwise returnfalse
.map.delete(key)
— Removes the value of the specified key.map.clear()
— Clear the map.map.size
— Returns the current number of elements.
let map = new Map(a); map.set('1'.'str1'); // String key
map.set(1.'num1'); / / the number keys
map.set(true.'bool1'); // Boolean key
// Remember the ordinary Object? It turns the key into a string
// Map keeps the key type, so these two results are different:
alert( map.get(1));// 'num1'
alert( map.get('1'));// 'str1'
alert( map.has(1));// 'true'
alert( map.size ); / / 3
Copy the code
Summary: **, ** keys in Map are not converted to strings. Keys can be of any type, including objects. Map [key] is not the correct way to map. This would treat the map as a plain object in JavaScript, and it would have no object key.
Let’s look at an example of an object key
let coolFish = { name: "coolFish" };
// Store the number of visits per user
let visitsCountMap = new Map(a);// John is a key in Map
visitsCountMap.set(coolFish, 123);
alert( visitsCountMap.get(coolFish) ); / / 123
Copy the code
How does Map compare keys? Map uses the SameValueZero algorithm to compare keys for equality. It’s the same thing as strictly equal ===, except NaN is treated as equal to NaN. So NaN can also be used as a key. The algorithm cannot be changed or customized. Each map.set call returns the map itself, so we can make chain calls.
map.set('1'.'str1')
.set(1.'num1')
.set(true.'bool1');
Copy the code
The Map iteration
If you want to use loops in a map, you can use the following three methods
- Map.keys () iterates over and returns all keys.
- Map.value () iterates over and returns all values.
- Map.entries () iterates through and returns all entities.
let coolFish = new Map([['age'.24],
['sex'.'male'],
['height'.178]]);// Iterate over all keys (vegetables)
for (let vegetable of coolFish.keys()) {
alert(vegetable); // age, sex, height
}
// go through all the values (amounts)
for (let amount of coolFish.values()) {
alert(amount); // 24, 'male ', 178
}
[key, value] [key, value]
for (let entry of coolFish) { // Same as recipemap.entries ()
alert(entry); // ['age', 24]
}
Copy the code
The order of iteration is the same as the order of insertion. Unlike ordinary objects, maps retain this order.
Object.entries: Create a Map from an Object
When a Map is created, we can pass in an array of key-value pairs or other iterable to initialize it, as shown below
// Array of key and value pairs
let map = new Map([['1'.'str1'],
[1.'num1'],
[true.'bool1']]); alert( map.get('1'));// str1
Copy the code
If we wanted to create a Map from an Object, we would use Object.entries(obj), which returns an array of key/value pairs for the Object in exactly the format required for the Map.
let obj = {
name: "coolFish".age: 24
};
let map = new Map(Object.entries(obj));
alert( map.get('name'));// coolFish
Copy the code
FromEntries allows us to create an Object from an array with [key, value].
let map = new Map(a); map.set('banana'.1);
map.set('orange'.2);
map.set('meat'.4);
//let obj = Object.fromEntries(map.entries()); Create a plain object (*)
let obj = Object.fromEntries(map); / / save. Entries ()
// Done!
// obj = { banana: 1, orange: 2, meat: 4 }
alert(obj.orange); / / 2
Copy the code
Calling map.entries() returns an iterable key/value pair, which is exactly the format required by Object.fromentries.
Set
Set basic attributes
Its main methods are as follows:
new Set(iterable)
Create aset
If provided with a可迭代
Object (usually an array) that copies values from the array toset
In the.set.add(value)
Add a value and return the set itselfset.delete(value)
— Delete the value ifvalue
Returns if it exists at the time of the method calltrue
Otherwise returnfalse
.set.has(value)
– ifvalue
In set, returntrue
Otherwise returnfalse
.set.clear()
— Clear set.set.size
— Returns the number of elements.
The main feature is that nothing changes when set.add(value) is called repeatedly with the same value. This is why each value in a Set appears only once.
let set = new Set(a);let john = { name: "John" };
let pete = { name: "Pete" };
let mary = { name: "Mary" };
// visits, some visitors visit several times
set.add(john);
set.add(pete);
set.add(mary);
set.add(john);
set.add(mary);
// set only holds non-repeating values
alert( set.size ); / / 3
for (let user of set) {
alert(user.name); // John (then Pete and Mary)
alert(user); //{name: "John"}
}
Copy the code
Set iteration
We can use for.. Of or forEach to iterate through a Set.
let set = new Set(["oranges"."apples"."bananas"]);
for (let value of set) alert(value);
// Same as forEach:
set.forEach((value, valueAgain, set) = > {
alert(value);
});
Copy the code
We can see that in the forEach callback, the current value and index are the same value, both of which are the current item, in order to easily replace Map with Set in certain cases, and vice versa.
set.keys()
Returns an iterable object for values.set.values()
– andset.keys()
It’s the same. It’s for compatibilityMap
.set.entries()
— Iterate and return an iterable object for entries[value, value]
It also exists for compatibilityMap
.
conclusion
Map – is a collection of data items with keys.
let coolFish = new Map([['age'.24],
['sex'.'male'],
['height'.178]]);Copy the code
Set – is a Set of unique values.
function unique(arr) {
return Array.from(new Set(arr));
}
let values = ["Hare"."Krishna"."Hare"."Krishna"."Krishna"."Krishna"."Hare"."Hare".":-O"
];
alert( unique(values) ); // Hare, Krishna, :-O
Copy the code
These are the basic features and uses of maps and sets.