Ways to create a Set in JavaScript?

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

    The first way is idiomatic JavaScript.

    Any time you want to store a key/value pair, you must use a JavaScript object. As for arrays, there are several problems:

    1. The index is a numerical value.

    2. No easy way to check to see if a value is in an array without looping through.

    3. A set doesn't allow duplicates. An array does.

    0 讨论(0)
  • 2021-01-31 07:37

    If you want to create a set from an array, simply do:

    let arr = [1, 1, 2, 1, 3];
    let mySet = new Set(arr); // Set { 1, 2, 3 }
    

    This is a sugar syntax that I quite fancied when programming in Python, so glad that ES6 finally made it possible to do the same thing.

    NOTE: then I realize what I said didn't directly answer your question. The reason you have this "hack" in ES5 is because lookup time in an object by keys is significantly faster (O(1)) than in an array (O(n)). In performance critical applications, you can sacrifice this bit of readability or intuition for better performance.

    But hey, welcome to 2017, where you can use proper Set in all major modern browsers now!

    0 讨论(0)
  • 2021-01-31 07:37

    Basic creation and usage of Set object

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