Is there any other way to access the collection of JavaScript, (Set), other than traversing?

after looking at the document, I found that JavaScript Set has Add, but it doesn"t seem to be as good as Map as it does not have Get,. What are the useful scenarios for this Set? I had hoped to use Set to create Enum-like features, but it seemed hopeless.

Mar.30,2021

Set is used to store unique value , the key point is unique, so there is .has method ( document ). As for .get , if you think about it, you will find that this semantics does not exist in Set, because Set is not a structure corresponding to keys and values.

the most typical scenario is the event listener:

  • discard duplicate registered listeners: Set data is unique
  • listeners call sequentially: Set traverses in insertion order
  • call all listeners: Set traversal is almost as fast as an array
  • add / remove frequently: Set add / remove quickly

so Set corresponds to an array, not an object.

< hr >

if I want to simulate Enum, I don't understand why I use Set at first. Then realize that you may want to control the enumeration value only. Then you should use Symbol:

// enum.ts
const enum Color {
  red,
  green,
  blue,
}
export default Color

// app.js
import Color from './enum.js';
const red = Color.red;      // -> const red = 0 /* red */;

but it also has the cost of learning, so it depends on whether you need it or not.

Menu