0

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!

Kevin
  • 229
  • 2
  • 10
  • 19

2 Answers2

3

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
David P. Caldwell
  • 3,394
  • 1
  • 19
  • 32
  • Ok, but it's not like this?... intData = ({ "A": 1, "B": 2, "C": 3})strData; – Kevin Dec 08 '14 at 16:49
  • Can be either. Property labels in JavaScript object literals can be quoted or not. Try it! – David P. Caldwell Dec 08 '14 at 21:28
  • It works exactly as you have written above. But I had to use "" for A, B, and C. Thank you David and have a nice day :-) – Kevin Dec 09 '14 at 09:03
  • I'm glad that was helpful. I couldn't tell what you meant about the double quotes. I'm updating my answer with an example I used from the Chrome debugger: does my syntax not work for you? – David P. Caldwell Dec 09 '14 at 15:17
1

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

var ENUM = Object.freeze({a: 1});
ENUM['a'];
kharandziuk
  • 12,020
  • 17
  • 63
  • 121