How to add an array of values to a Set

前端 未结 9 655
轮回少年
轮回少年 2020-12-29 02:15

The old school way of adding all values of an array into the Set is:

// for the sake of this example imagine this set was created somewhere else 
// and I ca         


        
9条回答
  •  别那么骄傲
    2020-12-29 02:24

    @Fuzzyma, I'll suggest you to use Prototyping of JavaScript to define new method on Set.

    Do not use in-built method name defined on Set.

    If you still prefer to use the same function name as in-built function name like add then the better approach would be to inherit the Set and override add() method.

    This is better way to add methods to existing objects without affecting their methods and use our own methods with same name. The charisma of Method overriding, a nice OOP concept.

    Here in the below code, I have defined addItems() on Set.

    Try it online at http://rextester.com/LGPQC98007.

    var arr = [3, 7, 8, 75, 65, 32, 98, 32, 3];
    var array = [100, 3, 200, 98, 65, 300]; 
    
    // Create a Set
    var mySet = new Set(arr);
    console.log(mySet);
    
    // Adding items of array to mySet
    Set.prototype.addItems = function(array) {
        for(var item of array){
            this.add(item)
        }
    }
    
    mySet.addItems(array);
    console.log(mySet)
    

    » Output

    Set { 3, 7, 8, 75, 65, 32, 98 }
    Set { 3, 7, 8, 75, 65, 32, 98, 100, 200, 300 }
    

提交回复
热议问题