Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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

like image 630
user1219627 Avatar asked Mar 02 '12 06:03

user1219627


People also ask

Can we use enums in JavaScript?

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.

When should we use enum in 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.

What is the point of using 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.

Should you use enums?

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.


1 Answers

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.

like image 87
Paul Avatar answered Oct 06 '22 10:10

Paul