问题描述
阅读处理在Javascript中,我仍然不确定,因为我可以将值与伪造值进行比较,而我只需要比较一个枚举类型值:
Reading the "recommended way" of dealing with ENUM Type in Javascript, I am still uncertain because I can compare the value with a forged value, while I should compare only to a "enum" type value:
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"
}
我将转换为(星期一,星期二,blahblahday)的字符串完全免于我的枚举类型:DaysEnum,可以由用户,这可能会导致一些未被解释器发现的微妙错误(如打字错误)。
The strings I made the switch to compare against ("monday", "tuesday", "blahblahday") are totally free from my "enum type: DaysEnum", can be provided by the user and this could lead to some subtle errors not spotted by the interpreter (like typos).
有没有办法拥有/锁定唯一的ind枚举对象的ex值?
Is there a way to have/lock unique index values of the Enum object?
推荐答案
使用ES2015发现的一个可能的解决方案可能是通过符号
A possible solution I found with ES2015 could be through Symbols
这样你就可以拥有独特的锁定值,就像您在其他语言中一样,像Java
This way you have the unique "locked" values, like you have in other languages, like 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
}
这篇关于有没有办法在Javascript中拥有/锁定Enum对象的唯一索引值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!