Reputation: 787
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
Upvotes: 6
Views: 11215
Reputation: 141827
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
.
Upvotes: 12