Search code examples
javascriptenumsmodular

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!


Solution

  • 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