Set (Set)

  1. Is a data structure called collections (new in ES6)
  2. Array.from, or ES6… Extended operators)
    const items = new Set([1.2.3.1])
    const array = Array.from(items)
    console.log(array)	/ / [1, 2, 3]
    / / or
    const arr = [...items]
    console.log(arr)	/ / [1, 2, 3]
    Copy the code
  3. Is itself a constructor used to generate a Set data structure
    new Set([iterable])
    Copy the code
  4. Members are unique, unordered, and non-repetitive
    const s = new Set([1.2.3.5.4.3.2.1]) //1 2 3 5 4
    Copy the code
  5. [value, value], the key value is the same as the key name (or only the key value, no key name)
  6. Allows you to store a unique value of any type, either a primitive value or an object reference
    new Set({a:"123".b:"1234"}){a:"123",b:"1234"} This is not iterable
    const s = new Set(a); s.add({a:"123".b:"1234"})// It works
    Copy the code
  7. You can iterate with for of
    const s = new Set([1.2.3.5.4.3.2.1]) //1 2 3 5 4
    for (let i of s) {
        console.log(i)	// 1 2 3 5 4
    }
    Copy the code
  8. When a value is added to a Set, no type conversion occurs
    let s = new Set()
    s.add(1)
    s.add('1')
    console.log([...s])	/ / / 1, "1"
    Copy the code
  9. The Set instance attributes are:
    1. Constructor: a constructor
    2. Size: number of elements
      let set = new Set([1.2.3.5.4.3.2.1])
      console.log(set.size)	/ / 3
      console.log(set.length)	// undefined
      Copy the code
    • Note: There is no length attribute
  10. You can add, delete, has, and clear
    1. Add (value) : adds a value, which is equivalent to push in an array
    2. Delete (value) : deletes the value in the collection
    3. Has (value) : Determines whether a value exists in the set
    4. Clear () : Clears the collection
    let set = new Set()
    set.add(1).add(2).add(3)
    set.has(1)	// true
    set.has(4)	// false
    set.delete(1)	
    set.has(1)	// false
    Copy the code
  11. Keys values entries forEach (Traversal order: insert order)
    1. Keys () : Returns an iterator containing all the keys in the collection
    2. Values () : Returns an iterator containing all the worth iterators in the setKeys with values () ()It’s the same thing becauseKey value and key nameIs consistent) as shown in the picture:
    3. Entries () : Returns a key-value iterator containing all the elements of the Set object
    The key and value structure is shown in the screenshot belowCopy the code

    4. ForEach (callbackFn, thisArg) : used to perform callbackFn on a collection member. If thisArg is provided, this in the callback would be this.No return value

  12. Set can be traversed by default, and the default iterator generator is the values() method
    Set.prototype[Symbol.iterator] === Set.prototype.values	// true
    Copy the code
  13. Set can use map and filter methods
  14. Intersect and Union can be easily implemented with Set.
    let set1 = new Set([1.2.3.5])
    let set2 = new Set([4.3.2.1])
    let intersect = new Set([...set1].filter(value= > set2.has(value)))
    let union = new Set([...set1, ...set2])
    console.log(intersect)	// Set(3) {1, 2, 3}
    console.log(union)		// Set(5) {1, 2, 3, 5, 4}
    Copy the code

WeakSet

  1. Members are objects
  2. Members are weak references that can be collected by the garbage collection mechanism and can be used to hold DOM nodes without causing memory leaks
  3. Can’t traverse
  4. The differences with Set are as follows:
    • WeakSet can only store object references, not values, but both Set values and objects can be stored
    • The object values stored in the WeakSet object are weakly referenced, that is, the garbage collection mechanism does not consider the application of WeakSet to the object. If there is no other variable or attribute referencing the object value, the object will be garbage collected (not considering the object still exists in the WeakSet), so, The number of member elements in the WeakSet object depends on whether the garbage collection mechanism is running. The number of members before and after the operation may be inconsistent. After the end of traversal, some members may not be taken (recycled by the garbage), and the WeakSet object cannot be traversed (ES6 specifies that WeakSet cannot be traversed). There’s no way to get all the elements it contains
  5. WeakSet instance attributes are:
    • Any object that has an Iterable interface can be used as an argument
  6. The operation methods include :add, delete, has,Clear method does not have
    1. Add (value) : Add an element value to the WeakSet object
    2. Has (value) : Determines whether a Value is included in a WeakSet object
    3. Delete (value) : deletes the value of the element
    4. Clear () : Clears all elements, noting that this method is deprecated
    var wst = new WeakSet(a)var obj = {}
    var abc = {}
    wst.add(window)
    wst.add(obj)
    wst.has(window)	// true
    wst.has(abc)	// false
    wst.delete(window)	// true
    wst.has(window)	// false
    Copy the code

The Map (dictionary)

  1. It’s a data structure called a dictionary
  2. It’s essentially a set of key-value pairs, sort of a set
  3. You can iterate, you can do a lot of things and you can convert to a lot of different data formats
  4. The Map instance attributes are:
    1. Constructor: a constructor
    2. Size: Returns the number of elements contained in the dictionary
    const map = new Map([['name'.'long'],
      ['age'.12]]); map.size/ / 2
    map.length /// undefined
    Copy the code
    • Note: There is no length attribute
  5. The Map operation method has: set, get, has, delete, clear
    1. Set (key, value) : Adds a new element to the dictionary
    2. Get (key) : Finds a specific value by key and returns it
    3. Has (key) : Checks whether the key exists in the dictionary
    4. Delete (key) : removes the corresponding data from the dictionary by key
    5. Clear () : Removes all elements from this dictionary
    const m = new Map(a)const o = {name: 'long'}
    m.set(o, 'liangliang')
    m.get(o)	// liangliang
    m.has(o)	// true
    m.delete(o)	// true
    m.has(o)	// false
    Copy the code
  6. Traversal methods are: the Keys and values, entries, forEach
    1. Keys() : Returns all key names contained in the dictionary as iterators
    2. Values () : Returns all values contained in the dictionary as iterators
    3. Entries () : Returns an iterator for all members
    4. ForEach (callbackFn,thisArg) : iterates through all members of the dictionary, performing callbackFn on the collection member. If thisArg is provided,this in the callback will be the thisArg argument, with no return value
    const map = new Map([['name'.'long'],
            ['age'.16]]);console.log(map.entries())//MapIterator {"name" => "long", "age" => 16}
    console.log(map.keys())//MapIterator {"name", "age"}
    console.log(qmap.values())//MapIterator {"long", 16}
    
    const reporter = {
      report: function(key, value) {
        console.log("Key: %s, Value: %s", key, value); }};let map = new Map([['name'.'long'],
        ['age'.16]])// Note that the this of the forEach callback refers to reporter
    map.forEach(function(value, key, map) {
      this.report(key, value);
    }, reporter);
    // Key: name, Value: long
    // Key: age, Value: 16
    Copy the code
  7. The default Map traverser interface (symbol. iterator property) is the entries method
    const map = new Map()
    map[Symbol.iterator] === map.entries // true
    Map.prototype[Symbol.iterator]  === Map.prototype.entries
    Copy the code
  8. Differences between sets and dictionaries:
    • Common: Collections, dictionaries can store values that are not duplicated
    • Differences: Collections store elements as [value, value], dictionaries as [key, value]
  9. Matters needing attention
    • The Map structure only treats references to the same object as the same key, which is easy to mistake
      const map = new Map(a); map.set(['a'].555);
      map.get(['a']) // undefined
      var scs = ['a'];
      map.set(scs , Awesome!);
      map.get(scs)/ / 666
      // Set and get methods, ostensibly for the same key, are actually two values,
      // The memory address is different, so the get method cannot read the key, returns undefined,
      // The second example is fine
      Copy the code
    • If the Map’s key is a value of a simple type (number, string, Boolean), the Map will treat the two values as one key as long as they are strictly equal, such as 0 and -0 being one key, and true and the string true being two different keys. Also,undefined and NULL are two different keys. Although NaN is not strictly equal to itself, Map treats it as the same key.
  10. Map and other data structures are converted as follows:
    1. Turn the Map Array
      const map = new Map([[1.1], [2.2], [3.3]])
      console.log([...map])	// [[1, 1], [2, 2], [3, 3]]
      Copy the code
    2. Array to the Map
      const map = new Map([[1.1], [2.2], [3.3]])
      console.log(map)	// Map {1 => 1, 2 => 2, 3 => 3}
      Copy the code
    3. Turn the Map Object
      • Since the key names of Object are strings and the key names of Map are objects, non-string keys are converted to string keys during conversion.
      function mapToObj(map) {
          let obj = Object.create(null)
          for (let [key, value] of map) {
              obj[key] = value
          }
          return obj
      }
      const map = new Map().set('name'.'long').set('age'.16)
      mapToObj(map) // {name: "long", age: "16"}
      Copy the code
    4. Turn the Object Map
      function objToMap(obj) {
          let map = new Map(a)for (let key of Object.keys(obj)) {
              map.set(key, obj[key])
          }
          return map
      }
      objToMap({'name': 'long'.'age': 16})
      // Map {"name" => "long", "age" => 16}
      Copy the code
    5. The Map to JSON
      function mapToJson(map) {
          return JSON.stringify([...map])
      }
      let map = new Map().set('name'.'LONG').set('age'.16)
      mapToJson(map)	// [["name","LONG"],["age",16]]
      Copy the code
    6. JSON to turn the Map
      function objToMap(obj) {
          let map = new Map(a)for (let key of Object.keys(obj)) {
              map.set(key, obj[key])
          }
          return map
      }
      function jsonToStrMap(jsonStr) {
        return objToMap(JSON.parse(jsonStr));
      }
      jsonToStrMap('{"name": "long", "age": 16}') 
      // Map {"name" => "long", "age" => 16}
      Copy the code

WeakMap

  1. Only objects (except null) are accepted as key names, and values of other types are not accepted as key names.
  2. The key name is a weak reference, the key value can be arbitrary, the object that the key name refers to can be garbage collected, in which case the key name is invalid.
  3. The methods are get, set, has, and delete.
  4. Note that WeakMap weakly references only the key name, not the key value. Key values are still normal references.
  5. In WeakMap, the reference of each key to its referenced object is weak. If there is no other reference and the key references the same object, the object will be garbage collected (the corresponding key becomes invalid). Therefore, the key of WeakMap is not enumerable.
  6. Properties:
    • Constructor: a constructor
  7. Methods:
    1. Has (key) : checks whether there is an object associated with the key
    2. Get (key) : returns the object associated with the key (undefined)
    3. Set (key) : Sets a group of key associated objects
    4. Delete (key) : deletes the object associated with the key
    let myElement = document.getElementById('logo');
    let myWeakmap = new WeakMap(a); myWeakmap.set(myElement, {timesClicked: 0});
    myElement.addEventListener('click'.function() {
      let logoData = myWeakmap.get(myElement);
      logoData.timesClicked++;
    }, false);
    Copy the code

conclusion

  1. These concepts are newly added, and it is difficult to remember them all at once. Our best memory is to use them, and we can use them successfully in our daily work
  2. Finally, if you like it, you can give it a thumbs up. Thank you