Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

javascript - 在JavaScript中定义枚举的首选语法是什么? [关闭](What is the preferred syntax for defining enums in JavaScript? [closed])

What is the preferred syntax for defining enums in JavaScript?(在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?(还是有更好的成语?)

  ask by David Citron translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since 1.8.5 it's possible to seal and freeze the object, so define the above as:(从1.8.5开始,可以密封和冻结对象,因此将以上定义为:)

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

or(要么)

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

and voila!(和瞧!)

JS enums.(JS枚举。)

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 .(确保类型安全性(使用枚举或其他方式)的程度更高的一种方法是使用诸如TypeScriptFlow之类的工具。)

Source(资源)

Quotes aren't needed but I kept them for consistency.(不需要引号,但为了保持一致性,我保留了它们。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...