SoFunction
Updated on 2025-03-06

One article will help you understand Map and Set in JS thoroughly

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

SetIt is a constructor itself, used to generateSetData structure

 let set = new Set();
 (set);  // {}

SetObjects can store values ​​of any type, but useSetThe 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...oforfor...in

 // traversal value for (let value of set) { (value);}
 // traversal key for (let key in set) {(key);}

Type conversion

SetTypes can be converted to other types of values

ArrayConvert toSet

 let arr = [1, 2, 3, 4]
 let set = new Set(arr)
 (set);  // { 1, 2, 3, 4 }

SetConvert toArray: It can be extended operator...To achieve

 let set = new Set([1, 2, 3, 4])
 ([...set]);  // [ 1, 2, 3, 4 ]

StringConvert toSet

 let str = 'Zhang San'
 let set = new Set(str)
 (set); // { 'Zhang', 'Three' }

The role of Set

Go to the heavy

useSetNon-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:SetCases are not allowed, 1 and '1' are considered different values

Set Summary

  • SetThe biggest feature is that its elements are unique, and based on this feature, it can be used to dereduce
  • SetIt can store any type of value, but only iterable objects can be passed in during initialization.
  • SetCan be withArrayConvert each other, you can alsoStringConvert toSettype
  • Extended operators and SetCombining structures to realize array or string deduplication

Map

Before ES6, key/value storage was implemented in js.ObjectTo complete efficiently, ES6 has added a new collection typeMap

Its biggest feature is:MapThe 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.

soObjectandMapKey value type:

  • ObjectString/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();

GiveMapThe 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

andObjectOne difference in type is:MapThe instance maintains the insertion order of key-value pairs, so iterative operations can be performed in sequence.

MapProvides 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

  • ObjectOnly two types of key names can be received:StringandSymbol
  • MapAble to accept key names of any type

MapKey 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'}

ObjectKey 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' }

AlthoughObjectIt can accept other types of key names, and js will implicitly convert them to strings at that time

Iteration

  • MapIt can be iterated, useforEachLoop orfor...of
  • ObjectIt cannot be iterated directly

ObjectThe 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...inTraversal key

 for (let key in obj) {
     (key); // namer age sex
 }

Order and length

length

  • MapSave tracking of length, you can use it directlysize, the time event complexity isO(1)
  • ForObjectFor example, if you want to obtain the length of the object, it needs to iterate over it, and its time complexity isO(n)

order

  • MapAlways keep the order of key-value pairs when inserting
  • ObjectNo, but after ES6, it can be saved in order, but the keys that are implicitly converted to strings are out of order.

Summarize

  • MapThe key can be of any type and can be usedforEachWait for iteration
  • MapThe key-value pair is based onsetSet the order of storage
  • MapGet the length justsizeThe attribute is returned directly, the time complexity isO(1)
  • MapThe disadvantage is that it cannot be used[]andpointTo set and get key values, onlysetandgetCome and replace
  • Fixed memory size,MapIt can be comparedObjectStore 50% more key-value pairs

WeakSet and WeakMap

WeakSet

WeakSetIt 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 

WeakSetNoneclearMethods andsizeproperty

becauseWeakSetThe value in  can be destroyed at any time, so there is no need to provide iterative functions, and there is no need to firstclearThis clear function

In addition, becauseWeakSetMembers of   can be recycled by the garbage collection mechanism, so they can be used to saveDOMNodes, not easy to cause memory leakage

WeakMap

weakMapyesMapTheir methods are basically the same,The difference is how internal distribution works

weakMapOnly 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

WeakMapNoneclearMethods andsizeproperty

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!