Mimicking sets in JavaScript?

前端 未结 7 2044
栀梦
栀梦 2020-11-22 13:01

I\'m working in JavaScript. I\'d like to store a list of unique, unordered string values, with the following properties:

  1. a fast way to ask \'is A in t
相关标签:
7条回答
  • 2020-11-22 13:43

    In ES6 version of Javascript you have built in type for set (check compatibility with your browser).

    var numbers = new Set([1, 2, 4]); // Set {1, 2, 4}
    

    To add an element to the set you simply use .add(), which runs in O(1) and either adds the element to set (if it does not exist) or does nothing if it is already there. You can add element of any type there (arrays, strings, numbers)

    numbers.add(4); // Set {1, 2, 4}
    numbers.add(6); // Set {1, 2, 4, 6}
    

    To check the number of elements in the set, you can simply use .size. Also runs in O(1)

    numbers.size; // 4
    

    To remove the element from the set use .delete(). It returns true if the value was there (and was removed), and false if the value did not exist. Also runs in O(1).

    numbers.delete(2); // true
    numbers.delete(2); // false
    

    To check whether the element exist in a set use .has(), which returns true if the element is in the set and false otherwise. Also runs in O(1).

    numbers.has(3); // false
    numbers.has(1); // true
    

    In addition to methods you wanted, there are few additional one:

    • numbers.clear(); would just remove all elements from the set
    • numbers.forEach(callback); iterating through the values of the set in insertion order
    • numbers.entries(); create an iterator of all the values
    • numbers.keys(); returns the keys of the set which is the same as numbers.values()

    There is also a Weakset which allows to add only object-type values.

    0 讨论(0)
提交回复
热议问题