Ways to create a Set in JavaScript?

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

提交回复
热议问题