6

I have the following ENUM in my Javascript:

var letters = { "A": 1, "B": 2, "C": 3.....}

And to use this I know use:

letters.A

But I was wondering if there was a way that i could replace A with a variable. I have tried something like

var input = "B";

letters.input;

but this does not work.

Any suggestions?

Thanks

2
  • Why would you expect letters.input to mean something when you never defined letters.input in the first place? Commented Mar 2, 2012 at 6:09
  • @AdamMihalcin letters is the enum and input is in replace of the hardcoded A in the first line. Commented Mar 2, 2012 at 6:11

1 Answer 1

12

You can use the Bracket Notation Member Operator:

letters[input];

It expects a string, so letters.B == letters["B"], and:

var letters = { "A": 1, "B": 2, "C": 3 },
    input = "B";
console.log(letters[input]);

outputs 2.

Sign up to request clarification or add additional context in comments.

1 Comment

@row1 I cant yet ... time limt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.