Causes:

JavaScript’s default object representation {} can be thought of as a Map or Dictionary data structure in other languages, a set of key-value pairs.

There is a slight problem with JavaScript objects, however, that the key must be a string. But the fact that Number or some other data type is a key makes perfect sense. To address this problem, the latest ES6 specification introduces new data types Map and SET.

A Set is a data structure called a collection, and a Map is a data structure called a dictionary

Application scenarios

Array de-duplication and data storage

Set [array of classes]

  • A set is a set of unordered and unique (that is, unrepeatable) items. You can think of a set as an array that has neither repeating elements nor any notion of order

    var a = new Set([1.2.3, {"1": "2"},"3"."4"]])
    Copy the code
  • ES6 provides a new data structure, Set. It is similar to an array, but the values of the members are unique and there are no duplicate values

  • The Set itself is a constructor used to generate the Set data structure

    A Set is the Set we’re talking about, so let’s look at the basics

    const s = new Set(a); [2.3.5.4.5.2.2].forEach(x= > s.add(x));
    
    for (let i of s) {
      console.log(i);   // 2 3 5 4
    }
    
    // Remove duplicate members of the array
    let array = [1.2.1.4.5.3];
    [...new Set(array)]     // [1, 2, 4, 5, 3]
    
    Copy the code
Method and attribute summaries
  • attribute

    Size: Returns the number of elements contained in the dictionary

  • Operation method

    1. Add (value) : Adds a value and returns the Set structure itself.

    2. Delete (value) : deletes a value and returns a Boolean value indicating whether the deletion is successful.

    3. Has (value) : Returns a Boolean value indicating whether the value is a member of Set.

    4. Clear () : Clears all members. No value is returned.

    5. Size: Returns the data length of the set data structure

      let set = new Set(a);console.log(set.add(1).add(2)); // Set [ 1, 2 ]
      
      console.log(set.delete(2)); // true
      console.log(set.has(2)); // false
      
      console.log(set.clear()); // undefined
      console.log(set.has(1)); // false
      console.log(set.size);  / / 0
      Copy the code
  • Traversal methods

    1. Keys () : returns a traverser for key names

    2. Values () : Iterator that returns key values

    3. Entries () : Returns a traverser for key and value pairs

    4. ForEach () : Iterates through each member using the callback function, with no return value

      let set = new Set(['a'.'b'.'c']);
      console.log(set.keys()); // SetIterator {"a", "b", "c"}
      console.log([...set.keys()]); // ["a", "b", "c"]
      Copy the code
      let set = new Set(['a'.'b'.'c']);
      console.log(set.values()); // SetIterator {"a", "b", "c"}
      console.log([...set.values()]); // ["a", "b", "c"]
      Copy the code
      let set = new Set(['a'.'b'.'c']);
      console.log(set.entries()); // SetIterator {"a", "b", "c"}
      console.log([...set.entries()]); // [["a", "a"], ["b", "b"], ["c", "c"]]
      Copy the code
      let set = new Set([1.2.3]);
      set.forEach((value, key) = > console.log(key + ':' + value));
      // 1: 1
      // 2: 2
      // 3: 3
      Copy the code
Method analysis (implementation principle)
  • Create a set

    function Set(arr = []) {    // You can pass in an array
        let items = {};
        this.size = 0;  // Record the number of members in the collection
    }
    
    module.exports = Set;
    Copy the code

    The {} object is used to represent collections because objects do not allow a key to point to two different attributes, ensuring that the elements in the collection are unique

  • From the way

    / / from the (val) method
    this.has = function (val) {
      // Objects have a hasOwnProperty method that determines whether they have a particular property
      return items.hasOwnProperty(val);
    };
    Copy the code
  • The add method

    / / add (val) method
    this.add = function (val) {
      if (!this.has(val)) {
        items[val] = val;
        this.size++; // Add the number of collection members
        return true;
      }
      return false;
    };
    
    Copy the code
  • Keys, values methods

    / / keys () method
    this.keys = function () {
      return Object.keys(items); // Returns an array of all the key names iterating through the collection
    };
    / / values () method
    this.values = function () {
      return Object.values(items); // Returns an array of keys iterating through the collection
    };
    Copy the code
  • The forEach method

    ForEach (fn, context)
    this.forEach = function(fn, context = this) {
        for (let i = 0; i < this.size; i++) {
            let item = Object.keys(items)[i]; fn.call(context, element, sameElement, set); }};Copy the code
  • Array.from()

    Convert an array of the Set class to a real array

    let arrayLike = {
        0: 'tom'.1: '65'.2: 'male'.3: ['jane'.'john'.'Mary'].'length': 4
    }
    let arr = Array.from(arrayLike)
    console.log(arr) / / [' Tom ', '65' and 'male', [' Jane ', 'John', 'Mary']]
    Copy the code
  • Relationship to Array

  • var myArray = ["value1"."value2"."value3"];
    
    // Convert an Array to a Set using the Set constructor
    var mySet = new Set(myArray);
    
    mySet.has("value1"); // returns true
    
    / / with... The (expansion operator) operator converts Set to Array
    console.log([...mySet]); // Same as myArray
    Copy the code
  • Advanced usage

    let set = new Set([2.1.3]);
    console.log(set.keys());    // ['1', '2', '3']
    console.log(set.values());  // [1, 2, 3]
    console.log(set.size);      / / 3
    set.delete(1);
    console.log(set.values());  // [2, 3]
    set.clear();
    console.log(set.size);      / / 0
    
    / / and set
    let a = [1.2.3];
    let b = new Set([4.3.2]);
    let union = new Set(a).union(b).values();
    console.log(union);     // [1, 2, 3, 4]
    / / or
    let a  = new Set([1.2.3.4])
    let b = new Set([4.5.6])
    let union = new Set([...a, ...b])
    console.log(union) //1, 2, 3, 4, 5, 6
    
    
    / / intersection
    let c = new Set([4.3.2]);
    let intersect = new Set([1.2.3]).intersect(c).values();
    console.log(intersect); // [2, 3]
    / / or
    let a = new Set([1.2.3.4])
    let b = new([4.5.6])
    let difference = [...a].filter(function(ele) {
      return b.has(ele);
    }) / / 4
    // Arrow function
    let difference = [...a].filter(x= > x.has(x)) / / 4
    
    / / difference set
    let d = new Set([4.3.2]);
    let difference = new Set([1.2.3]).difference(d).values();
    // the difference between [1,2,3] and [4,3,2] is 1
    console.log(difference);    / / [1]
    / / or
    let a = new Set([1.2.3.4])
    let b = new([4.5.6])
    let difference = [...a].filter(function (ele) {
      return! b.has(ele); })/ / 1, 2, 3
    Copy the code

Map (dictionary)[class object]

It is a collection of key-value pairs similar to objects, but the scope of “keys” is not limited to strings. Values of all types (including objects) can be used as keys, which is a more complete implementation of Hash structures. If you need key-value data structures, Map is better than Object;

So what’s the difference between a set and a dictionary?

  • Common: Collections and dictionaries can store values that are not duplicated

  • Differences: Collections store elements as values, dictionaries as keys

    A Set is the Set we’re talking about, so let’s look at the basics

    const m = new Map(a);const o = {p: 'Hello World'};
    m.set(o, 'content')
    m.get(o) // "content"
    
    m.has(o) // true
    m.delete(o) // true
    m.has(o) // false
    Copy the code
Method and attribute summaries
  • attribute

    Size: Returns the number of elements contained in the dictionary

  • Operation method

    1. Set (key, val): Adds a new element to the dictionary

    2. Get (key): Finds a specific value by key value and returns it

    3. Has (key): Returns true if the key exists in the dictionary, false otherwise

    4. Delete (key): Removes the corresponding data from the dictionary by key value

    5. Clear (): Removes all elements from this dictionary

    6. let m = new Map(a); m.set('Jay'.'the Jay Chou');
      m.set(true.'really');
      console.log(m.has('Chou')); // false
      console.log(m.size); / / 2
      console.log(m.keys()); // [ 'Jay', 'true' ]
      console.log(m.values()); // [ 'Jay的Chou', '真的' ]
      console.log(m.get('jay')); // undefined
      
      m.delete(true);
      console.log(m.keys()); // [ 'Jay' ]
      console.log(m.values()); // ['Jay Chou']
      Copy the code

      If you add a value to a key multiple times, the subsequent value will flush out the previous value:

      var m = new Map(a); m.set('Adam'.67);
      m.set('Adam'.88);
      m.get('Adam'); / / 88
      Copy the code

      The Map method takes a two-dimensional array as an argument

      var m = new Map([['name'.'zhangsan'], ['sex'.'male']]);
      console.log(m); //Map {"name" => "zhangsan", "sex" => "male"}
      Copy the code
  • Traversal methods

    1. Keys (): Returns all the key names contained in the dictionary as an array

    2. Values (): Returns all values contained in the dictionary as an array

    3. Entries () : Returns a traverser for key and value pairs

    4. ForEach () : Traverses all the members of the dictionary

      var map = new Map([['age'.19], ['height'.180]]);
      
      for (let key of map.keys()) {
        console.log(key); // age height
      }
      
      for (let value of map.values()) {
        console.log(value); / / 19, 180
      }
      
      for (let item of map.entries()) {
        console.log(`${ item[0]}: ${ item[1]}`);  //age: 19 height: 180
      }
      
      for (let [key, value] of map.entries()) {
        console.log(`${ key }: ${ value }`); //age: 19 height: 180
      }
      
      for (let [key, value] of map) {
        console.log(`${ key }: ${ value }`); //age: 19 height: 180
      }
      
      map.forEach((value, key, map) = > {
        console.log(`${ key }: ${ value }`); //age: 19 height: 180
      });
      Copy the code
Method analysis (implementation principle)
  • Build a dictionary

    function Map() {
        let items = {};
    }
    
    module.exports = Map;   / / export
    Copy the code
  • From the way

    / / from the (key) method
    this.has = function (val) {
      return items.hasOwnProperty(val);
    };
    Copy the code
  • Set and get methods

    // set(key, val)
    // Set the same key
    New Map().set({}, 'a')
    this.set = function (key, val) {
      items[key] = val;
    };
    / / get (key) method
    this.get = function (key) {
      // Check whether there is a key, if so, return the corresponding value
      If an unknown key is read, undefined is returned
      return this.has(key) ? items[key] : undefined;
    };
    Copy the code
  • Keys, values methods

    / / keys () method
    this.keys = function () {
      return Object.keys(items); // Returns an array of all the key names iterating through the collection
    };
    / / values () method
    this.values = function () {
      return Object.values(items); // Returns an array of keys iterating through the collection
    };
    
    Copy the code
  • The forEach method

    ForEach (fn, context)
    this.forEach = function(fn, context = this) {
        for (let i = 0; i < this.size; i++) {
            let item = Object.keys(items)[i]; fn.call(context, element, sameElement, set); }};Copy the code
  • Relationship to Array

    / / the Map array
    const map = new Map(a); map.set('name' , 'hello').set({},'world');
    
    [...map] //[["name","hello"],[{},"world"]]
    [...map.value()] //[["hello","world"]
    
    // Array to Map
    const map = new Map([["name"."hello"], [{},"world"]]);
    
    map // {"name" => "hello", Object {} => "world"}
    Copy the code
  • Relationships with objects

    //Map to object method
    function strMapToObj(strMap) {
      let obj = Object.create(null);
      for (let [k,v] of strMap) {
        obj[k] = v;
      }
      return obj;
    }
    let myMap = new Map().set('name'.'Virgo').set('old'.'18');
    console.log(strMapToObj(myMap));// { name: "Virgo", old: "18"}
    
    // Object to Map method
    function objToStrMap(obj) {
      let strMap = new Map(a);for (let k of Object.keys(obj)) {
        strMap.set(k, obj[k]);
      }
      return strMap;
    }
    var a = {name: 'Virgo'.old: '18'}
    console.log(objToStrMap(a))//Map(2){"name" => "Virgo", "old" => "18"}
    Copy the code