Using Enums In Javascript

I have the following ENUM in my Javascript:

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

And to use this, I know:

letters.A

But I was wondering if there is a way to replace A with a variable. I tried something like

var input = "B";

letters.input;

but it does not work.

Any suggestions?

thank

+5
source share
1 answer

You can use the operator Operator-Member-Index with binding to brackets :

letters[input];

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

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

exits 2.

+11
source

All Articles