狐狸.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 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配