Kevin
Kevin

Reputation: 229

Enum in Javascript

In Javascript I'm going to read data (strData). But the data are String values, but I have to work with Integer values.

For example:

intData = strData;

...where strData could be "A", "B", or "C".

But intData should be 1 for "A", 2 for "B", or 3 for "C".

I could just do an If-else statement, but I have to get strData very often. In this case, I always have to "if-else" the content of strData. So I need something to keep the code as short as possible. An one-time allocation of the Integer values to the String values. How I have to impelement that?

Thanks for your help!

Upvotes: 0

Views: 274

Answers (2)

David P. Caldwell
David P. Caldwell

Reputation: 3829

intData = ({ A: 1, B: 2, C: 3})[strData]

For example (transcript from Chrome debugger console):

>  (function() { var strData = "C"; return ({ A: 1, B: 2, C: 3})[strData]; })()
<- 3

Upvotes: 3

kharandziuk
kharandziuk

Reputation: 12890

I think you should use Object.Freeze with plain object:

var ENUM = Object.freeze({a: 1});
ENUM['a'];

Upvotes: 1

Related Questions