有没有办法在Javascript中拥有/锁定Enum对象的唯一索引值?

Sim*_*ggi 8 javascript enums

阅读在Javascript 中处理ENUM类型"推荐方法",我仍然不确定,因为我可以将值与伪造值进行比较,而我应该只比较"枚举"类型值:

 var DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, ...}
 Object.freeze(DaysEnum)

 switch( day ){
   case "monday":
     return "Hello"
   case "tuesday":
     return "Hi"
   case "blahblahday":
     return "No"
 }
Run Code Online (Sandbox Code Playgroud)

我进行比较的字符串("星期一","星期二","blahblahday")完全没有我的"枚举类型:DaysEnum",可以由用户提供,这可能会导致一些未发现的细微错误由翻译(如拼写错误).

有没有办法拥有/锁定Enum对象的唯一索引值?

Sim*_*ggi 4

我在 ES2015 中发现的一个可能的解决方案是通过 Symbols

http://putaindecode.io/en/articles/js/es2015/symbols/

这样你就拥有了独特的“锁定”值,就像在其他语言(如 Java)中一样

 const DAY_MONDAY = Symbol();
 const DAY_TUESDAY = Symbol();

 switch(animal) {
   case DAY_MONDAY:
     return "Hello"
   case DAY_TUESDAY:
     return "Hi"
   //there is no way you can go wrong with DAY_BLAHBLAHDAY 
   //the compiler will notice it and throw an error
 }
Run Code Online (Sandbox Code Playgroud)