definition
Set is a data structure called a collection (the structure is very similar to Array). The elements in the Set are unique, that is, there are no duplications (this is very important).
Map is a data structure called a dictionary, which saves key-value pairs like Object, but the range of keys in MapNot limited to stringsTypes, various types of values (including objects) can be treated as a key or a value
Set
Set
It is a constructor itself, used to generateSet
Data structure
let set = new Set(); (set); // {}
Set
Objects can store values of any type, but useSet
The parameters passed in the constructor can only be iterable objects, such as arrays, strings
// When you pass an integer, js will tell you that the parameter 1 passed in is not an iterable object let set = new Set(1); (set); // number 1 is not iterable // An error will be reported by passing in the object let set = new Set({}); (set); // object is not iterable // Must be an array or string, let set1 = new Set('1'); (set1); let set2 = new Set([1, 'true']); (set2);
Common methods
method | illustrate | Example |
---|---|---|
has() | Determine whether there is this value and return a boolean value | ('name') |
add() | Add elements to Set(), if there is the same, it will be overwritten | ('name', 'zxc') |
delete | Used to delete an element, return true if successful, and return false if failed. | ('name') |
clear() | Used to clear all members in Set(), no return value | () |
size attribute | Determine how many elements Set() has |
let set = new Set() let arr = [1, 2] (1).add(arr) (function() { (123); }) ({}) (set); // { 1, [ 1, 2 ], [Function (anonymous)], {} } // has() judges elements ((arr)); // true // size judges length (); // 4 // delete ((1)); // true ((arr)); // true, the objects stored in set can only be deleted with clear address index, otherwise you can only use clear() // clear () (set); // {}
Order and iteration
Set()
There are four ways to traverse the structure
method | illustrate | Example |
---|---|---|
keys() | Return key traverser | () |
values() | The return value traverser | () |
entries() | Returns the traverser of all members, including keys and values | () |
forEach | Iterate through all members of Set | (function(), [this]) |
Since the Set structure has no key name, its key name and key value are the same
let set = new Set(['Zhang San', 'Li Si', 'Wang Wu', 'true']); // traversal key (()); // { 'Zhang San', 'Li Si', 'Wang Wu', 'true' } // traversal value (()); // { 'Zhang San', 'Li Si', 'Wang Wu', 'true' } // Return key value (()); /* { [ 'Zhang San', 'Zhang San' ], ['Li Si', 'Li Si'], [ 'Wang Wu', 'Wang Wu'], [ 'true', 'true' ] }*/ // forEach() loop let set = new Set(['Zhang San', 'Li Si', 'Wang Wu', 'true']) (function(value, key) { (key + ':' + value); }) /* Zhang San: Zhang San Li Si: Li Si Wang Wu: Wang Wu true:tru*/
Can also be usedfor...of
orfor...in
// traversal value for (let value of set) { (value);} // traversal key for (let key in set) {(key);}
Type conversion
Set
Types can be converted to other types of values
Array
Convert toSet
let arr = [1, 2, 3, 4] let set = new Set(arr) (set); // { 1, 2, 3, 4 }
Set
Convert toArray
: It can be extended operator...
To achieve
let set = new Set([1, 2, 3, 4]) ([...set]); // [ 1, 2, 3, 4 ]
String
Convert toSet
let str = 'Zhang San' let set = new Set(str) (set); // { 'Zhang', 'Three' }
The role of Set
Go to the heavy
useSet
Non-repeatability can be used to deduplicate arrays
// Convert the array to Set, and then convert the Set to an array let arr = [1, 1, 4, 1, 2, 3, 1, 2] let set = new Set(arr) ([...set]); // [ 1, 4, 2, 3 ]
Collect
let arr1 = [1, 1, 4, '1', 2, 3] let arr2 = [5, 1, '2'] let set = new Set([...arr1, ...arr2]) ([...set]); // [ 1, 4, '1', 2, 3, 5, '2' ]
PS:Set
Cases are not allowed, 1 and '1' are considered different values
Set Summary
-
Set
The biggest feature is that its elements are unique, and based on this feature, it can be used to dereduce -
Set
It can store any type of value, but only iterable objects can be passed in during initialization. -
Set
Can be withArray
Convert each other, you can alsoString
Convert toSet
type - Extended operators and
Set
Combining structures to realize array or string deduplication
Map
Before ES6, key/value storage was implemented in js.Object
To complete efficiently, ES6 has added a new collection typeMap
Its biggest feature is:Map
The range of the middle key is not limited to string type. Values of various types (including objects) can be regarded as a key or a value.
soObject
andMap
Key value type:
-
Object
:String/Symbol type: any type
-
Map
:Any type: Any type
Initialize the map
Create an empty map
// It must be created this way let map= new Map();
GiveMap
The constructor passes in an iterable object, which needs to contain key-value pairs. Each key-value pair will be mapped to the instance in the iterative order.
const map = new Map([ ['name', 'cyf'], ['age', 18] ]); (map); // {"name" => "zxc", "age" => 18}
Common methods for Map
method | illustrate | Example |
---|---|---|
get() | Get the value by key, if there is no key, it returns undefined | ('name') |
has() | Determine whether the key is present and return the Boolean value | ('name') |
set() | Used to set the corresponding key value pair, if there is the same, it will be overwritten | ('name', 'zxc') |
delete() | Used to delete a key, return true if successful, return false if failed. | ('name') |
clear() | Used to clear all members in Map(), no return value | () |
let map = new Map([ ['namer', 'Zhang San'], ['age', 2] ]); // Get namer (('namer')); // Zhang San //Judge namer (('age')); // 2 // Set key-value pairs (('sex', 'other')); // { 'namer' => 'Zhang San', 'age' => 2, 'sex' => 'Other' }// Continuously set (('id', 0).set('hobby', 'Telling jokes')); // size attribute to get map length (); // 5 // Delete a key (('id')); // true // Clear map () (map); // {}
A key can only correspond to one value. If you put a value on a key multiple times, the previous value will be overwritten.
let map =new Map() ('Amy',"female") ('Amy',"male") (map)
Order and iteration
andObject
One difference in type is:Map
The instance maintains the insertion order of key-value pairs, so iterative operations can be performed in sequence.
Map
Provides 3 traversers and one traversal method
method | illustrate | Example |
---|---|---|
keys() | Return key traverser | () |
values() | The return value traverser | () |
entries() | Returns the traverser of all members, including keys and values | () |
forEach | Iterate through all members of the Map | (function(), [this]) |
let map = new Map().set('namer', 'Zhang San').set('age', 2).set('sex', 'other') // Get key let keys = () (keys); // Get the value let values = () (values); // Get key-value pairs (()); // { [ 'namer', 'Zhang San' ], [ 'age', 2 ], [ 'sex', 'other' ] } for (let [key, value] of map) { (key + ':' + value); } // namer: Zhang San // age:2 // sex:Others // forEach loop (function(value, index) { (index + ':' + value); }) // namer: Zhang San // age:2 // sex:Others
The difference between Map and Object
Key name type
-
Object
Only two types of key names can be received:String
andSymbol
-
Map
Able to accept key names of any type
Map
Key name:
let map = new Map(); (1, 'Number').set(true, 'Boolean').set({ 'Key name': 'Key Value' }, 'Object').set(function() {}, 'Function') (map); // { 1 => 'Number', true => 'Boolean', { 'Key name': 'Key value' } => 'Object', [Function (anonymous)] => 'Function'}
Object
Key name
let obj = {} obj[1] = 'Number'; obj[true] = 'Boolean'; obj[{ 'Key name': 'Key Value' }] = 'Object'; obj[function() {}] = 'Function' (obj); // { '1': 'Number', true: 'Boolean', '[object Object]': 'Object', 'function() {}': 'Function' }
AlthoughObject
It can accept other types of key names, and js will implicitly convert them to strings at that time
Iteration
-
Map
It can be iterated, useforEach
Loop orfor...of
-
Object
It cannot be iterated directly
Object
The static method that requires the help of objects
let obj = { 'namer': 'Zhang San', 'age': 2, 'sex': 'other' } // traversal key for (let key of (obj)) { (key); }
It can also be:
for (let value of (obj)) {} for (let keyValue of (obj)) {} for (let [key, value] of (obj)) {}
Of course it can be usedfor...in
Traversal key
for (let key in obj) { (key); // namer age sex }
Order and length
length
-
Map
Save tracking of length, you can use it directlysize
, the time event complexity isO(1)
- For
Object
For example, if you want to obtain the length of the object, it needs to iterate over it, and its time complexity isO(n)
order
-
Map
Always keep the order of key-value pairs when inserting -
Object
No, but after ES6, it can be saved in order, but the keys that are implicitly converted to strings are out of order.
Summarize
-
Map
The key can be of any type and can be usedforEach
Wait for iteration -
Map
The key-value pair is based onset
Set the order of storage -
Map
Get the length justsize
The attribute is returned directly, the time complexity isO(1)
-
Map
The disadvantage is that it cannot be used[]
andpoint
To set and get key values, onlyset
andget
Come and replace - Fixed memory size,
Map
It can be comparedObject
Store 50% more key-value pairs
WeakSet and WeakMap
WeakSet
WeakSet
It is a "weak collection" type, and the values in the collection can only be objects
Since the Set structure has no key name, its key name and key value are the same
let set = new Set(['Zhang San', 'Li Si', 'Wang Wu', 'true'])
method | illustrate |
---|---|
has() | Determine whether there is this value and return a boolean value |
add() | Add elements to Set(), if there is the same, it will be overwritten |
delete() | Used to delete an element, return true if successful, return false if failed. |
1. Create an empty oneWeakSet
let WeakSet = new WeakSet();
2. InitializationWeakSet
The constructor can pass in an iterative object, and the value in the iterable object must be an object.
let x = { id: 1 }, y = { id: 2 } let weakSet = new WeakSet([x, y]); (weakSet); ((x)); // true ((x)); // true
WeakSet
Noneclear
Methods andsize
property
becauseWeakSet
The value in can be destroyed at any time, so there is no need to provide iterative functions, and there is no need to firstclear
This clear function
In addition, becauseWeakSet
Members of can be recycled by the garbage collection mechanism, so they can be used to saveDOM
Nodes, not easy to cause memory leakage
WeakMap
weakMap
yesMap
Their methods are basically the same,The difference is how internal distribution works
weakMap
Only accept data of reference type as key names, such as arrays, functions, objects, etc.
1. Create an empty oneWeakMap
let WeakMap = new WeakMap();
2. InitializationWeakMap
let weakMap = new WeakMap(); let x = { id: 1 }, y = { id: 2 } (x, 'Zhang San') (y, 2) ((x)); // Zhang San ((y)); // 2 ((x)); // true ((x)); // true
WeakMap
Noneclear
Methods andsize
property
This is the article about this article about how to thoroughly understand Map and Set in JS. This is all about this article. For more related JS Map Set content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!