ES6 new features -Set and Map

Set

1. ES6 provides a Set data container, which is an ordered list of non-repeating values.

2. Set related apis

  • throughconst set=new Set()You can create a Set object
  • Or throughConst set = new set ([1, 2, 3])create
  • set.add(x)Used to add data items to a set. Set internal useObject.is()Method to determine whether two items are equal. The only difference is that +0 and -0 are equal in a Set.
  • set.has(x)Used to determine whether a set contains a value
  • set.sizeTo get the amount of data inside a Set
  • set.delete(x)Used to delete a value from a set
  • set.forEach(()=>{})The argument used to traverse the set callback is the element value; Element index; The object to be traversed;
Let set = new set ([1,2,3,3,3,3]); set.forEach(function (value,key,ownerSet) { console.log(value); console.log(key); })Copy the code
  • set.clear()To clear the set
  • Set [x]=x Set [x]=x
  • Also through[...arr]=setConvert a set to an array arr

Weak Set

Cause of occurrence

When a Set stores objects, it actually stores references to objects. That is, it is also called a Strong Set. If the stored object is Set to NULL, but the Set instance still exists, the object cannot be collected by the garbage collector and thus cannot free memory:

let set = new Set(); let key={}; let key2 = {}; set.add(key); set.add(key2); console.log(set.size); //2 key=null; console.log(set.size); / / 2Copy the code

Weak Set ** holds Weak references to the object. If the object is only weakly referenced by the Set, it does not prevent the object instance from being recycled. ** The usage of Ser and Weak Set is almost the same

Weak Set Difference between Weak Set and Set

  • For Weak Set instances, an error is thrown if the add() method is called with a non-object argument. Returns false if a non-object argument is passed to a has() or delete() method;
  • Weak sets are not iterable and therefore cannot be used for for-of loops;
  • Weak sets do not expose any iterators (such as keys() and values() methods), so there is no way to determine the contents of a Weak Set;
  • Weak Set has no forEach() method;
  • Weak Set does not have size;

Map

1.ES6 provides a Map data structure, which can store key-value pairs. Key reduplication is compared through object.is () method.

2. The Map API

  • Initialize, similar to Setlet map = new Map()or
/ / use the array to create the Map let Map = new Map ([[' title ', 'hello world'], [' year ', '2018']]). console.log(map.has('title')); //true console.log(map.has('year')); //true console.log(map.size); / / 2Copy the code
  • Same as Set, also hashas('key').delete('key')As well asclear()methods
  • map.set('key','value')Used to add key-value pairs
  • map.get('key')Used to get key=’key’
 let map = new Map();
 map.set('title','hello world');
 map.set('year','2018');
 
 console.log(map.get('title')); // hello world
Copy the code
  • Like Set, Map has a forEach method, which also receives a callback function that takes three arguments: the element value; Element index; The object to be traversed
 let map = new Map([['title','hello world'],['year','2018']]);
 map.forEach((value,key,ownerMap)=>{
     console.log(value);
     console.log(key);
 });
 
 hello world
 title
 2018
 year
Copy the code

Weak Map

Cause of occurrence

Weak Map to Map is the same as Weak Set to Set: Weak maps (or Weak sets) are all ways of storing Weak references to objects. In a Weak Map(or Weak Set), all keys must be objects (trying to use a key that is not an object will throw an error), and these objects are Weak references and do not interfere with garbage collection. When a key in an Weak Map is not referenced outside the Weak Map, the key-value pair is removed.

Weak Map usage

  • Weak Map initialization
// Use an array to create a Weak Map let key = {}; let key2 = {}; let map = new WeakMap([[key,'hello'],[key2,'world']]); console.log(map.get(key)); //hello console.log(map.get(key2)); //worldCopy the code
  • Has method and delete method
let key2 = {};
let map = new WeakMap([[key,'hello'],[key2,'world']]);

map.delete(key);
console.log(map.has(key)); //false
Copy the code

Weak Map usage and limitations

  • When deciding whether to use Weak Map or Map, the primary consideration is whether you only want to use keys of object types.
  • If you’re going to do this, the best option is Weak Map. Because it ensures that additional data is destroyed after it is no longer available, it optimizes memory usage and avoids memory leaks.

Keep in mind that Weak maps provide very little visibility into their content, so you can’t use the forEach() method, the size attribute, or the clear() method to manage items. If you do need some detection, a regular Map is a better choice, just be sure to keep an eye on memory usage.

summary

  1. A Set is an ordered list of no duplicate values, according toObject.is()To determine the inequality of the internal values. availablehas()To determine whether a value is in a Set, or to usesizeSee how many values are in the Set. Set can still be usedforEach()To process each value.
  2. A Map is an ordered key-value pair in which keys are allowed to be of any type. Similar to Set, according toObject.is()To determine the internal bonds are not equal, and notice,Value of 1withA string of 1It could be two separate bonds. useset()Method can associate any type of value to a key and should be used laterget()Method to extract. Map also has onesizeAttributes and aforEach()Method to make project access easier.
  3. Weak sets are special sets that contain only objects. The objects are stored by weak references and therefore do not mask the garbage collection mechanism. However, due to the complexity of memory management, the contents of the Weak Set cannot be checked.
  4. Weak maps are special maps that contain only keys of the object type. Like Weak sets, an object reference to a key is a Weak reference, so it is not shielded from garbage collection when it is the only surviving reference to an object. When the key is reclaimed, the associated value is also removed from the Weak Map.