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!

0

2 Answers 2

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 
Sign up to request clarification or add additional context in comments.

4 Comments

Ok, but it's not like this?... intData = ({ "A": 1, "B": 2, "C": 3})strData;
Can be either. Property labels in JavaScript object literals can be quoted or not. Try it!
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 :-)
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?
1

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.