How to add an array of values to a Set

前端 未结 9 759
轮回少年
轮回少年 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:30

    There's currently no addAll method for Sets, but you have two options to simplify your life when working with them. The first one would be to extend the prototype. Before you do that, read this post and decide afterwards if the possible consequences are ok for your project/intended use.

    if (!Set.prototype.addAll) {
      Set.prototype.addAll = function(items) {
        if (!Array.isArray(items)) throw new TypeError('passed item is not an array');
        // or (not sure what the real Set.prototype will get sometime)
        // if (!Array.isArray(items)) items = [items];
        for (let it of items) {
          this.add(it);
        }
        return this;
      }
    }
    

    If you decided not to extend the prototype, just create a function that you can reuse in your project

    function addAll(_set, items) {
        // check set and items
        for (let it of items) {
             _set.add(it);
        }
        return _set;
    }
    

提交回复
热议问题