Ways to create a Set in JavaScript?

后端 未结 9 474
太阳男子
太阳男子 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:19

    I use dict objects as sets. This works with strings and numbers, but I suppose would cause problems if you wanted to have a set of objects using custom equality and comparison operators:

    Creating a set:

    var example_set = 
    {
        'a':true,
        'b':true,
        'c':true
    }
    

    Testing for inclusion in a set

    if( example_set['a'] ){
        alert('"a" is in set');
    }
    

    Adding an element to a set

    example_set['d'] = true;
    

    Removing an element from a set

    delete example_set['a'];

提交回复
热议问题