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
Enums or Enumerated types are special data types that set variables as a set of predefined constants. In other languages enumerated data types are provided to use in this application. Javascript does not have enum types directly in it, but we can implement similar types like enums through javascript.
Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.
Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command-line flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time. A Java enumeration is a class type.
You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on. The output is: Mondays are bad.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With