Detailed es6 the difference and usage set, map, WeakSet, Weakmap of

set, map, WeakSet, Weakmap frequency of use js higher and higher, special equipment is some of the source code in the new framework, this blog will be the difference between its basic usage and make a summary, enhance memory.

set

set definition and characteristics of

  • Set in the js store any type of object allows unique value , whether it is the original value or object reference.
  • Top-level data structure does not have key-> value feature, automatically add the internal sequence index.
  • Any data can be stored in different types.

How to understand the unique nature: for the original data type (boolean, number, string, null, undefined) only if the stored value is the same as a stored, for reference types do "==" Analyzing i.e., identical references will only address a memory.

   let set = new Set();  
//a,b属于object 值完全相同
    let a = {
        name:"cc",
        age:28
    };
    let b = {
        name:"cc",
        age:28
    };
   
//c,d属于number类型 值完全相同
    let c = 0,d = 0;
//e,f 属于Date类型,值相同
    let e=f = new Date();

    set.add(a);
    set.add(b);
    set.add(c);
    set.add(d);
    set.add(e);
    set.add(f);

    a= "abc";
    b = {
        name:"cc",
        age:30
    }
    set.add(a);
    set.add(b);

    console.log(set);

Here Insert Picture Description
set method

  • size attributes: returns the number of elements of the set. (Length similar to the length of the array)
  • the Add (value) Method: add an element to the set value. NOTE: If you add elements to an existing collection, but the collection will not change without an error.
  • delete (value): Remove the element value from the collection.
  • has (value) Method: determining whether the value in the collection, return true or false.
  • clear () method: empty set.

set scenarios

Given the repetitive nature is not stored value set, it is often used to seek to re-array intersection and union, difference and other operations.

  1. Deduplication Array
let arry = [1, 2, 3, 4, 4,1,2,3,2];
var mySet = new Set(arry);
 let newArry = [...mySet]; // [1, 2, 3, 4]
  1. Seek union, intersection, difference.
    //set求并集
    let arryA= [2,3,4,5,6],arryB = [3,4,5,6,7,8];
    let setAB = new Set([...arryA,...arryB]);
    let newArryAB = [...setAB];
    console.log(newArryAB); //[2,3,4,5,6,7,8]

    //求交集
    let arryC= [2,3,4,5,6],arryD = [3,4,5,6,7,8];
    let setC = new Set(arryC);
    let setD = new Set(arryD);
    let newArryC_D = arryA.filter(x=>setD.has(x));
    console.log(newArryC_D); //[3,4,5,6]

    //求差集
    let newArryD_C = arryA.filter(x=>!setD.has(x));
    let newArryD_D = arryB.filter(x=>!setC.has(x));
    let newArryCD = [...newArryD_C,...newArryD_D];
    console.log(newArryCD); //[2,7,8]

map

map definition and characteristics of

Map object holds pairs. Any value (or the original target value) can be used as a key or a value.

Map CRUD common attributes and methods:

  • size: attribute, the length of the dictionary removed
  • set (key, value): method, add a new element to the dictionary
  • get (key): a method to find a specific key value and returns via
  • has (key): if there are key method the key is determined dictionary
  • delete (key): a method to remove from the dictionary data corresponding to the key by key
  • clear (): method, all the elements of this dictionary deleted

Object of the differences:

  • Object of the key can only be a string or Symbols, but a Map key can be any value.
  • Map of the keys are ordered (FIFO principle), and added to the object key is not.
  • Map key-values ​​can be obtained from the number of size attributes, and only manually Object key values ​​calculated for the number.
  • Object has its own prototype, the key name on the prototype chain and possible conflict in your own set of keys on the object, and map health can not be repeated, the corresponding value if the key name will be overwritten conflict.
let map = new Map();
    let s = {
        name:'cc',
        job:'programmer'
    }
    let m ={
        dd:'cdcdcd',
        do:function(str){
            console.log(str)
        }
    }
    map.set(s,m);
    map.set(m,s);
    map.set(0,s);
    map.set(0,m);
    console.log(map)

Here Insert Picture Description
map traversal

for … of
forEach

 for(let [key,value] of map){
        console.log("key:"+JSON.stringify(key)+"-------value:"+JSON.stringify(value))
    }

  map.forEach((value,key)=>{
      console.log("key:"+JSON.stringify(key)+"-------value:"+JSON.stringify(value))
  })

Conversion map between the array and

 let arryK = [[1,2],[3,4],[5,6]];

    let mapK = new Map(arryK);

    let mapP = Array.from(mapK);

    console.log(mapK);
    console.log(mapP);

Here Insert Picture Description
map copy

let mapV= new Map(map);

WeakSet

And Set structurally similar, it is not repeated set of values, but can only be a member of WeakSet object.

WeakSet the API: add () // add; delete () // delete; has () // if there is

Note: ws no size property, can not traverse. Because the members WeakSet are weak references, could disappear at any time, members are unstable.

WeakSet of use :
(1) Use a DOM node ws store, do not worry node is removed from the document, it will lead to memory leaks (that is, binding on the node is removed click events, etc.).
(2) The following code is an example of a method of Foo guaranteed, can only be called on an instance in Foo. The benefits of using WeakSet Here, foos a reference to the instance, it will not be included in the memory recovery mechanism, so delete instances when, regardless of foos, not a memory leak.

WeakSet

Map of the difference WeakMap:
WeakMap objects is a set of key-value pairs, wherein the reference object is a weak bond, and may be any value.

Note , WeakMap weak references only keys, instead of keys. The key is still normal reference.

WeakMap, each key is a reference to his own weak references of the referenced object, and in no other references to this key reference the same object, the object will be garbage (corresponding key becomes invalid), so, WeakMap the key is not enumerable.

Private property is achieved by WeakMap

    //weakmap

    let Person = (function() {

        let privateData = new WeakMap();

        function Person(name,age) {
            privateData.set(this,  {name:name,age:age});
        }

        Person.prototype.getName = function() {
            return privateData.get(this).name;
        };
        Person.prototype.getAge = function() {
            return privateData.get(this).age;
        };
        Person.prototype.setName = function(name) {
            let obj = privateData.get(this)
            obj.name = name;
        };
        Person.prototype.setAge = function(age) {
            let obj = privateData.get(this)
            obj.age = age;
        };

        return Person;
    }());

 let ssf = new Person("zhang",19);
    console.log(ssf.getName());
    console.log(ssf.getAge());
    ssf.setName("liu");
    ssf.setAge(90)
    console.log(ssf.getName());
    console.log(ssf.getAge());

Here Insert Picture Description

Published 69 original articles · won praise 6 · views 2725

Guess you like

Origin blog.csdn.net/weixin_40073115/article/details/104014232