1. Set collection
1. Basic usage
Set
:Set object allows you toStore any type of value, whether it is a primitive value or an object reference. Similar to an array, but the values of the members are unique and there are no duplicate values.
Set itself is a constructor used to generate the Set data structure.
const s = new Set();
[2, 3, 5, 4, 5, 2, 2].forEach(x => s.add(x));
for (let i of s) {
console.log(i);
}
// 2 3 5 4
2. Properties and methods
add(value)
: add a value, returnThe Set structure itself.
delete(value)
: delete a value, return aBoolean value, indicating whether the deletion was successful.
has(value)
: Returns a Boolean indicating whether the value is Set
a member of .
clear()
: Clear all members, no return value.
s.add(1).add(2).add(2);
// 注意2被加入了两次
s.size // 2
s.has(1) // true
s.has(2) // true
s.has(3) // false
s.delete(2);
s.has(2) // false
Array.from
method to convert Set
a structure into an array.
const items = new Set([1, 2, 3, 4, 5]);
const array = Array.from(items);
This provides another way to remove duplicate members from an array.
function dedupe(array) {
return Array.from(new Set(array));
}
dedupe([1, 1, 2, 3]) // [1, 2, 3]
3. traverse
Set.prototype.keys()
:returnkey namethe traverser;Set.prototype.values()
:returnkey valuethe traverser;Set.prototype.entries()
: returns a traverser of key-value pairs;Set.prototype.forEach()
: Use the callback function to traverse each member;- Use
for...of
direct traversal of Set;
Note: set
Only the key value or key name and key value are the same value
(1)keys(),values(),entries()
let set = new Set(['red', 'green', 'blue']);
// 键名
for (let item of set.keys()) {
console.log(item);
}
// red
// green
// blue
// 键值
for (let item of set.values()) {
console.log(item);
}
// red
// green
// blue
// 键值对
for (let item of set.entries()) {
console.log(item);
}
// ["red", "red"]
// ["green", "green"]
// ["blue", "blue"]
Traversing the Set directly with for...of
a loop
let set = new Set(['red', 'green', 'blue']);
for (let x of set) {
console.log(x);
}
// red
// green
// blue
(2)forEach()
let set = new Set([1, 4, 9]);
set.forEach((value, key) => console.log(key + ' : ' + value))
// 1 : 1
// 4 : 4
// 9 : 9
(3) The application of traversal
The spread operator (…) internally uses the for…of loop , so it can also be used for the Set structure.
let set = new Set(['red', 'green', 'blue']);
let arr = [...set];
// ['red', 'green', 'blue']
4. Application
1. Array deduplication
Combining the spread operator and the Set structure, you canRemove duplicate members from an array。
let arr = [3, 5, 2, 2, 5, 5];
let unique = [...new Set(arr)];
// [3, 5, 2]
2. Merge two Set objects
let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);
let union = new Set([...a, ...b]); // {1, 2, 3, 4}
2. WeakSet
WeakSet structure is similar to Set, alsocollection of unique values. However, it is different from Set.
1. Difference
- Members of a WeakSet can only be objects, not values of other types.
- The objects in the WeakSet are all weak references, that is, the garbage collection mechanism does not consider the WeakSet's reference to the object, that is, if other objects no longer refer to the object, the garbage collection mechanism will automatically reclaim the memory occupied by the object. The object is not considered to still exist
WeakSet
in .
Reason: This is because the garbage collection mechanism judges recycling based on the reachability of the object. If the object can still be accessed, the garbage collection mechanism will not release the memory. When you're done using the value, you sometimes forget to dereference it, preventing the memory from being freed, which can lead to a memory leak. The references in the WeakSet are not included in the garbage collection mechanism, so there is no such problem. Therefore, WeakSet is suitable for temporarily storing a group of objects and storing information bound to objects. As soon as these objects disappear externally, its reference inside the WeakSet will automatically disappear. - ES6 stipulates that WeakSet cannot be traversed。
2. Grammar
const ws = new WeakSet();
const a = [[1, 2],[3, 4]]
const ws = new WeakSet(a)
Note that this a is an array, and it has two members, both of which are arrays. If a is used as a parameter of the WeakSet constructor, the members of a will automatically become members of the WeakSet. The members of the a array become members of the WeakSet, not the a array itself. This means that the members of an array can only be objects.
// 数组b的成员不是对象,加入 WeakSet 就会报错。
const b = [3, 4];
const ws = new WeakSet(b);
console.log(ws) // 报错 Uncaught TypeError: Invalid value used in weak set(…)
method
WeakSet.prototype.add(value)
:Add toWeakSet.prototype.detele(value)
:deleteWeakSet.prototype.has(value)
: Returns a Boolean value indicating whether a value is present in the instance.- WeakSet has no
size
properties and no way to iterate over its members
2. Map
1. Meaning and basic usage
Similar to an object, it is also a collection of key-value pairs, but objects are generally 'string-value'. The Map structure provides a 'value-value' correspondence.
2. Instance attributes and operation methods
-
size
attribute`Returns the total number of members of the Map structure
-
set(key, value)
Add, if the key has a value, the key value will be updated, otherwise a new key will be generated and the current
Map
object will be returned, so it can be written in and chain. -
get(key)
get
The method readskey
the corresponding key value, if not foundkey
, returns undefined. -
has(key)
has
The method returns a Boolean value indicating whether a key is in the currentMap
object. -
delete(key)
delete
The method deletes a key and returnstrue
. Returns if deletion failsfalse
. -
clear()
clear
method clears all members and has no return value.
3. traverse
and Set
something like:keys(),values(),entries(),forEach()
const map = new Map([
['F', 'no'],
['T', 'yes'],
]);
for (let key of map.keys()) {
console.log(key);
}
// "F"
// "T"
for (let value of map.values()) {
console.log(value);
}
// "no"
// "yes"
for (let item of map.entries()) {
console.log(item[0], item[1]);
}
// "F" "no"
// "T" "yes"
// 或者
for (let [key, value] of map.entries()) {
console.log(key, value);
}
// "F" "no"
// "T" "yes"
Map
You can directly use for...of
the traversal
// 等同于使用map.entries()
for (let [key, value] of map) {
console.log(key, value);
}
// "F" "no"
// "T" "yes"
If Map
the structure is an array structure, we can use the spread operator ( ...
)
const map = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
]);
[...map.keys()]
// [1, 2, 3]
[...map.values()]
// ['one', 'two', 'three']
[...map.entries()]
// [[1,'one'], [2, 'two'], [3, 'three']]
[...map]
// [[1,'one'], [2, 'two'], [3, 'three']]
4. Interconversion with other data structures
(1) Convert Map to Array
The most convenient way is to use the spread operator ( ...
).
(2) Convert array to Map
Pass the array into the Map constructor
(3) Map converted to object
If there is a non-string key name, then this key name will be converted into a string and then used as the key name of the object.
const map = new Map([
['F', 'no'],
['T', 'yes'],
]);
let obj = Object.create(null);
for(let [key,value] of map){
obj[key] = value;
}
console.log(obj); //结果
(4) Convert the object to Map
able to passObject.entries()
let obj = {
"a": 1, "b": 2};
let map = new Map(Object.entries(obj));
4. WeakMap
1. Difference:
- WeakMap only accepts objects as keys (except null), and does not accept other types of values as keys.
const map = new WeakMap();
map.set(1, 2) // TypeError: 1 is not an object!
map.set(Symbol(), 2) // TypeError: Invalid value used as weak map key
map.set(null, 2) // TypeError: Invalid value used as weak map key
- The object pointed to by the key name of the WeakMap is not included in the garbage collection mechanism.
The difference between Set and Map
Map
It is a key-value pair,Set
which is a collection of keys. Of course, the key and value can be any value;Map
The value can be obtained throughget
the method, butSet
not because it only has the value;- can be traversed through iterators
for…of
; Set
The value is the only one that can doArray deduplication,Map
since there is no format restriction, one can dodata storage;map
Both andset
are associative containers in stl,map
stored in the form of key-value pairs,key=value
forming a pair, which is a set of mapping relationships.set
There is only one value, and it can be considered that there is only one data, andset
the elements in it cannot be repeated and are automatically sorted.