狐狸.fox 2008-11-13 19:09 采纳率: 0%
浏览 1306
已采纳

在 JavaScript 中定义 enum 的首选语法是什么?

What is the preferred syntax for defining enums in JavaScript? Something like:

my.namespace.ColorEnum = {
    RED : 0,
    GREEN : 1,
    BLUE : 2
}

// later on

if(currentColor == my.namespace.ColorEnum.RED) {
   // whatever
}

Or is there a more preferable idiom?

转载于:https://stackoverflow.com/questions/287903/what-is-the-preferred-syntax-for-defining-enums-in-javascript

  • 写回答

28条回答 默认 最新

  • 关注

    Since 1.8.5 it's possible to seal and freeze the object, so define the above as:

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

    or

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

    and voila! JS enums.

    However, this doesn't prevent you from assigning an undesired value to a variable, which is often the main goal of enums:

    let day = DaysEnum.tuesday
    day = 298832342 // goes through without any errors
    

    One way to ensure a stronger degree of type safety (with enums or otherwise) is to use a tool like TypeScript or Flow.

    Source

    Quotes aren't needed but I kept them for consistency.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(27条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器