current position:Home>JavaScript ES6 set (set) type* ω *

JavaScript ES6 set (set) type* ω *

2022-04-29 10:32:35XianZhe_

 Insert picture description here

Javascript ES6 aggregate (SET) type * ω *


One 、 aggregate

aggregate (Set), yes ES6 New data type in , This is the same as the concept of set in Mathematics .
In the interpretation of the JS Before the collection of , I think it's still necessary to review the main categories in the mathematical set first : Combine , intersection , Difference set
 Insert picture description here
JavaScript Set properties

  • Set yes ES6 New data structure provided , Allow any data type to be stored .
  • Natural weight loss , Each element is unique , Different from each other , This is also the main feature of the set .
  • Its elements can be iterated according to the insertion order .

Brief overview : A collection is an unordered and non repeating data type


Two 、 Take advantage of its de duplication

As mentioned above , The collection is born to lose weight , Then we can use the de duplication of sets to do something

  • Array weight removal :
    Zhang San used a cover up , Made several fake Zhang San , Let's see how Miss Luo treats Zhang San

    // const name = [' Zhang San ', ' Zhang San ', ' Zhang San ', ' Zhang San ', ' Zhang San ', ' Zhang San ', ' Zhang San ', ' Zhang San ', ' Zhang San ', ' Zhang San ', ' Luo Xiang ']
    let names = Array(10).fill(" Zhang San ", 0, 10)             //  You can also add multiple sheets in this way 
    names.push(" Luo Xiang ");
    names = [...new Set(names)]
    console.log(names)
    
    [" Zhang San ", " Luo Xiang "]
    

    Is that so? , You can crack Zhang San's deception by using a collection , Find out the only Zhang San

  • Next, let's look at an application of de duplication , Don't repeat the lottery

    const res = new Set();
    const names = [" Zhang San ", " Li Si ", " Xiao Ming ", " Li Hua ", " John ", "Jone", "Mark", "Bill", "PrettyGirl"];
    while (res.size < 3) {
          
        res.add(names[Math.abs(parseInt(Math.random() * 8))])
    }
    console.log(res)
    

    The program logic : Using the random Pick a name at random , Add this name to the collection , If it is repeated, no adding operation will be performed , The circulation condition is to judge whether the number of people in the collection is less than 3


3、 ... and 、 iteration Set

Before explaining the following , It is necessary to understand the data structure in the collection .

  • First of all, we should understand that the traditional index method cannot extract the set data .

     const vegetable = new Set([" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "]);
     for (let i=0; i < vegetable.size; i++) {
          
         //  Unable to remove ,  The output is undefined
         console.log(vegetable[i])
     }
    
  • Because the collection has no index , Use for in The value of the loop is also unavailable .

    const vegetable = new Set([" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "]);
    //  Loop not executed 
    for (let key in vegetable) {
          
        console.log(key)
    }
    
  • Only use for of Take values in a circular way , To have results

    const vegetable = new Set([" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "]);
    for (let value of vegetable) {
          
        console.log(value)
    }
    
     Green vegetables 
     radish 
     Apple 
     Banana 
     potatoes 
     a mandarin orange 
    

Four 、 Methods for collecting instance objects

1)、Set.prototype.add(value)

stay Set Add an element at the end of the object , And return to the Set object .

const vegetable = new Set([" Green vegetables ", " radish "]);
vegetable.add(" Apple ");
console.log(vegetable);

The... Will be returned according to the Set The principle of objects , Can be achieved for this Set Chain operation of object .

const vegetable = new Set([" Green vegetables ", " radish "]);
vegetable.add(" Apple ").add(" Banana ").add(" potatoes ").add(" a mandarin orange ");
console.log(vegetable);
{" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "}

2)、Set.prototype.clear()

remove Set All elements in the object .

const vegetable = new Set([" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "]);
vegetable.clear();
console.log(vegetable);     //  The collection is empty after emptying 

3)、Set.prototype.delete(value)

Remove the element in the collection equal to this value , And return whether the deletion was successful .
Before deleting , The program will execute first Set.prototype.has(value), Determine whether the element to be deleted exists , If the element exists , After deleting the element, it returns true, Otherwise return to false.

const vegetable = new Set([" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "]);
const r1 = vegetable.delete(" radish ");
const r2 = vegetable.delete(" Bro ");
console.log(r1, r2);
true false

4)、Set.prototype.entries()

Returns a new iterator object , This object contains the values of all elements in the collection object in insertion order [value, value] Array , Because only values exist in a set , So the elements in the array are equal .

const vegetable = new Set([" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "]);
for (let [key, value] of vegetable.entries()) {
    
    console.log(key, value);
}

5)、Set.prototype.forEach(callbackFn[, thisArg])

In insertion order , by Set Every value in the object is called once callBackFn. If provided thisArg Parameters , In callback this It's going to be this parameter .

The parameters are as follows :

  • callbackFn: Callback function executed for each element in the collection , This function takes three parameters :
    • currentValue: The element being manipulated .
    • currentKey: Because the collection has no index , therefore currentKey This element is also represented by .
    • set: Call current forEach Method .
  • thisArg: During the execution of callback function this value .

Demo code :

vegetable.forEach(function (currentValue, currentKey, set) {
    
    console.log(currentValue, currentKey, set)
})
 Green vegetables   Green vegetables  Set(6){' Green vegetables ', ' radish ', ' Apple ', ' Banana ', ' potatoes ',…}
 radish   radish  Set(6){' Green vegetables ', ' radish ', ' Apple ', ' Banana ', ' potatoes ',…}
......

6)、Set.prototype.has(value)

Returns a Boolean value , Indicates that the value is in Set Whether it exists in .

const vegetable = new Set([" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "]);
console.log(vegetable.has(" potatoes "));       // true
console.log(vegetable.has(" Bean soil "));       // false

7)、Set.prototype.keys()

Because only values exist in a set , And values() In the same way , Returns a new iterator object , The object contains Set The values of all elements in the insertion order of the object .

const vegetable = new Set([" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "]);
for (let item of vegetable.keys()) {
    
    console.log(item)
}
 Green vegetables 
 radish 
 Apple 
 Banana 
 potatoes 
 a mandarin orange 

8)、Set.prototype.values()

Returns a new iterator object , The object contains Set The values of all elements in the insertion order of the object .

const vegetable = new Set([" Green vegetables ", " radish ", " Apple ", " Banana ", " potatoes ", " a mandarin orange "]);
for (let item of vegetable.values()) {
    
    console.log(item)
}
 Green vegetables 
 radish 
 Apple 
 Banana 
 potatoes 
 a mandarin orange 

9)、Set.prototype[@@iterator]()

Returns a new iterator object , The object contains Set The values of all elements in the insertion order of the object . Usage and Set.prototype.keys() and Set.prototype.values() The method is the same .

for (let item of vegetable[Symbol.iterator]()) {
    
    console.log(item)
}
 Green vegetables 
 radish 
 Apple 
 Banana 
 potatoes 
 a mandarin orange 

actually ,Set.prototype.keys() and Set.prototype.values() Method return is also an iterator object , The data content is consistent . Use next() Methods observe .

const iterator = vegetable[Symbol.iterator]()
console.log("iterator:", iterator.next())
console.log("iterator:", iterator.next())

const keys = vegetable.keys()
console.log("keys:", keys.next())
console.log("keys:", keys.next())

const values = vegetable.values()
console.log("values:", values.next())
console.log("values:", values.next())

5、 ... and 、 Extended set method

1)、 Add methods to the collection prototype

/** *  to update (update) aggregate , Add from  others  All elements in ,  Inspiration comes from Python * @param others:  Iteratable object  * @return {Set<any>}  After adding results, the collection  */
Set.prototype.update = function (others) {
    
    if (others.constructor === Set) {
    
        for (let i of others) {
    
            this.add(i);
        }
    } else {
    
        for (let i = 0; i < others.length; i++) {
    
            this.add(others[i]);
        }
    }
    return this
}

/** *  Update collection , Removal also exists in  others  The elements in , That is, remove the elements that exist in both collections  * @param elems  Another set that needs to be updated  * @return {Set<any>}  Return to the new set  */
Set.prototype.difference_update = function (elems) {
    
    for (let e of elems) {
    
        if (this.has(e)) {
    
            this.delete(e);
        } else {
    
            this.add(e);
        }
    }
    return this
}

/** *  Returns the difference set method of the set ,  Inspiration comes from Python * @param set  Another set to compare  * @returns {Set<any>}  Difference set  */
Set.prototype.difference = function (set) {
    
    const diff = new Set();
    for (let item of set) {
    
        if (!this.has(item)) {
    
            diff.add(item);
        }
    }
    return diff
}

/** *  Returns the intersection method of the set ,  Inspiration comes from Python * @param set  Another set to compare  * @returns {Set<any>}  Intersection set  */
Set.prototype.intersection = function (set) {
    
    const common = new Set();
    for (let item of set) {
    
        if (this.has(item)) {
    
            common.add(item);
        }
    }
    return common
}

/** *  Returns the union method of the set ,  Inspiration comes from Python * @param set  Another set that needs to be merged  * @returns {Set<any>}  Merge sets  */
Set.prototype.union = function (set) {
    
    return this.update(set)
}

/** *  Get collection length  * @return {number}  Length value  */
Set.prototype.length = function () {
    
    return this.size;
}

2)、 Inherit
If you want to extend the method of the collection without affecting the original collection constructor , You can extend a collection by inheriting it .

class MySet extends Set {
    
    /** *  to update (update) aggregate , Add from  others  All elements in ,  Inspiration comes from Python * @param others:  Iteratable object  * @return {Set<any>}  After adding results, the collection  */
    update(others) {
    
        if (others.constructor === Set) {
    
            for (let i of others) {
    
                this.add(i);
            }
        } else {
    
            for (let i = 0; i < others.length; i++) {
    
                this.add(others[i]);
            }
        }
        return this
    }

    /** *  Update collection , Removal also exists in  others  The elements in , That is, remove the elements that exist in both collections  * @param elems  Another set that needs to be updated  * @return {Set<any>}  Return to the new set  */
    difference_update(elems) {
    
        for (let e of elems) {
    
            if (this.has(e)) {
    
                this.delete(e);
            } else {
    
                this.add(e);
            }
        }
        return this
    }

    /** *  Returns the difference set method of the set ,  Inspiration comes from Python * @param set  Another set to compare  * @returns {Set<any>}  Difference set  */
    difference(set) {
    
        const diff = new Set();
        for (let item of set) {
    
            if (!this.has(item)) {
    
                diff.add(item);
            }
        }
        return diff
    }

    /** *  Returns the intersection method of the set ,  Inspiration comes from Python * @param set  Another set to compare  * @returns {Set<any>}  Intersection set  */
    intersection(set) {
    
        const common = new Set();
        for (let item of set) {
    
            if (this.has(item)) {
    
                common.add(item);
            }
        }
        return common
    }

    /** *  Returns the union method of the set ,  Inspiration comes from Python * @param set  Another set that needs to be merged  * @returns {Set<any>}  Merge sets  */
    union(set) {
    
        return this.update(set)
    }

    length() {
    
        return this.size;
    }
}

Reference material

Official documents :


Related blog

copyright notice
author[XianZhe_],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204290916526758.html

Random recommended