How to add an array of values to a Set

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

    Just post that here for inspiration .. Creating a class that extends Set, and add a addRange method.

        class MegaSet extends Set {
        
          constructor(iterable) {
           super(iterable);
          }
          
          addRange(range) {
            for (var elem of range) {
              this.add(elem);
            }
          }
        }
        
        const array = [1,2,3,5,5,6];
        let mySet = new MegaSet([1,2,3,4]);
        
        mySet.addRange(array);
        console.log([...mySet]);

提交回复
热议问题