Ways to create a Set in JavaScript?

后端 未结 9 464
太阳男子
太阳男子 2021-01-31 07:06

In Eloquent JavaScript, Chapter 4, a set of values is created by creating an object and storing the values as property names, assigning arbitrary values (e.g. true) as property

9条回答
  •  梦如初夏
    2021-01-31 07:24

    Sets in ES6/ES2015:

    ES6/ES2015 now has built in sets. A set is data structure which allows storage of unique values of any type, whether this are primitive values or object references. A set can be declared using the ES6 built in set constructor in the following manner:

    const set = new Set([1, 2, 3, 4, 5]);
    

    When creating a set using the Set constructor our newly created set object inherits from the Set.prototype. This has all sorts of auxiliary methods and properties. This allows you to easily do the following things:

    Example:

    const set = new Set([1, 2, 3, 4, 5]);
    
    // checkout the size of the set
    console.log('size is: ' + set.size);
    
    // has method returns a boolean, true if the item is in the set
    console.log(set.has(1));
    
    // add a number
    set.add(6);
    
    // delete a number
    set.delete(1);
    
    // iterate over each element using a callback
    set.forEach((el) => {
      console.log(el);
    });
    
    // remove all the entries from the set
    set.clear();

    Browser compatibility:

    All major browser now fully support sets except IE where some features are missing. For exact reference please refer to the mdn docs.

提交回复
热议问题