ES6-6.Set set and Map set

1, Set set

Set set is an unordered list containing multiple duplicate values, which can quickly access the data and track various discrete values more effectively
1. Create a Set collection and add elements

    //Since there is no forced type conversion on the stored value in the set set, the number 5 and the string '5' can exist as independent elements
    let set = new Set();
    set.add(5);
    set.add('5');
    console.log(set.size);       //2  

    //Because there is no cast, you can add multiple objects
    let set = new Set(),
        key1 = {},
        key2 = {};
    set.add(key1);    
    set.add(key2);
    console.log(set.size);      //2

    //When the add() method is called multiple times and the same value is added, the Set collection is added only once
    let set  = new Set();
    set.add(5);   
    set.add('5');   
    set.add(5);        //add ignored this time
    console.log(set.size);       //2

2. has(), delete(), clear() method

The has() method determines whether a value exists in the Set

The delete() method deletes an element in the Set set

The clear() method removes all elements from the collection

3. forEach() method of Set

    //Use the forEach() method to iterate over each element in the output Set set
    // The forEach() method has three parameters
    // 1. The position of the next index in the Set;
    // 2. The same value as the first parameter;
    // 3. The traversed Set itself
    
    let set = new Set([1,2]);
    set.forEach(function(value, key, ownerSet){
        console.log(key + "" + value);
        console.log(ownerSet === set);

    });
    //Every time the callback function executes, the output keys and values are consistent. The ownerSet is always equal to the set. The output contents are as follows
    // 1 1
    // true
    // 2 2
    // true

If you want to use this in the forEach callback, you need to pass it in, but if you use the arrow function, you don't need to pass it in, as shown in the following code:

    // If you do not use the arrow function, you need to pass in this
    // Here, the forEach method only needs the first parameter value

    let set = new Set([1, 2]);
    let processor = {
        output(value){
            console.log(value);
        },
        //Pass this into the value of this as the callback function, thus this The output () method can be called to the processor correctly Output() method
        //If this is not passed in, an error will be reported
        process(dataSet){
            dataSet.forEach(function(value){
                this.output(value);
            }, this)
        }
    };

    processor.process(set);     // 1,2

    //If you use the arrow function, you do not need to pass in this

    let set = new Set([1,2]);
    let processor = {
        output(value){
            console.log(value);
        },
        process(dataSet){
            //The arrow function reads the value of this from the peripheral process() function, which points to the processor object
            dataSet.forEach(value => this.output(value));
        }
    };

    processor.process(set);      //1, 2

4. Convert Set set to array

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

    console.log(array);     //[1,2,3,4,5]

    //Using this feature, you can copy an array and return a new array without repetition

    function eliminateDuplicates(items){
        return [...new Set(items)];
    };

    let numbers = [1, 2, 3, 3, 3, 4, 5],
        noDuplicates = eliminateDuplicates(numbers);

    console.log(noDuplicates);    //[1,2,3,4,5]

5. Weak Set
Variables and objects saved in the Set set exist in the Set set even if the initial object is recycled or released. For example, the following code:

    let set = new Set(),
        key = {};

    set.add(key);
    console.log(set.size);     //1

    //The original reference is removed, but the Set collection retains the reference
    key = null;
    console.log(set.size);     //Output or 1
    
    //To retrieve the original reference, you can still use the expansion operator to convert the Set set to array format and take the reference from the first element of the array
    key = [...set][0];

So sometimes, when we clarify the original reference, we also hope that the Set collection will also be recycled by the garbage collection mechanism. At this time, the break Set set can be used. When the original reference is Set to null and cleared, the break Set set Set will be recycled by the garbage collection mechanism.

The initialization of Weak Set is the same as that of Set. It supports the methods of add(), has(), and delete(). But there are several points to note:

The Weak Set collection does not support passing in non object parameters, and an error will be reported.

The Weak Set set cannot be iterated, so a for of loop cannot be used.

The Weak Set collection does not expose any iterators.

The break set collection does not support the forEach() method.

The size property is not supported in the Weak Set collection.

So when you only need to track object references, you should use the Weak Set set rather than the ordinary Set set.

2, Map collection

Map is an ordered list that stores many key value pairs. The key names and corresponding values support all data types. So when the key names are 5 and "5", this is two independent keys. It will not be forcibly converted to a string like an object.

1. Initialization and addition

   let map = new Map();
    map.set('title', 'Understanding ECMAScript6');
    map.set('year', '2016');

    console.log(map.get('title'));     //Understanding ECMAScript6
    console.log(map.get('year'));      //2016
    
    //Similarly, Map can be used for objects as keys
    let map = new Map(),
        key1 = {},
        key2= {};

    map.set(key1, 5);
    map.set(key2, 42);

    console.log(map.get(key1));     //5
    console.log(map.get(key2));     //42

2. Supported methods

has(key) checks whether the specified key name already exists in the Map collection

delete(key) removes the specified key name and its corresponding value from the Map collection

clear() removes all key value pairs in the Map collection

3. Initialization method of Map collection
You can pass in array initialization, for example:

    let map = new Map([['name, Nicholas'], ['age, 25']]);
    
    console.log(map.has('name'));      //true
    console.log(map.get('name'));      //'Nicholas'
    console.log(map.has('age'));       //true
    console.log(map.get('age'));       //25
    console.log(map.size);             //2

4. forEach() method of Map collection
Similar to the forEach method of Set, for example:

    let map = new Map([['name',  'Nicholas'], ['age', 25]]);

    map.forEach(function(value, key, ownerMap){
        console.log(key + '' + value);
        console.log(ownerMap === map);      
    });

    // name 'Nicholas'
    // true
    //age  25
    //true

5. Weak Map set
The key name in the Weak Map collection must be an object. If a non object key name is used, an error will be reported.

The biggest use of the break map collection is to save Dom elements in Web pages. For some libraries, if you customize some Dom elements, you can use the break map collection to save them.

Supported methods: has(), delete(), clear()

Keywords: Javascript Front-end ECMAScript

Added by ryan-uk on Fri, 28 Jan 2022 11:04:35 +0200