Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript enumerator?

Tags:

javascript

I want to define a list of constants that have continuous integer value, for example:

var config.type = {"RED": 0, "BLUE" : 1, "YELLO" : 2};  

But it's boring to add a "XX" : y every time I need to add a new element in it.
So I'm wondering is there something like enumerator in C so I can just write:
var config.type = {"RED", "BLUE", "YELLO"} and they are given unique integer value automatically.

like image 529
wong2 Avatar asked Jun 14 '11 16:06

wong2


People also ask

What is enum in JavaScript example?

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.

What is the use of enumerator?

Enumerations make for clearer and more readable code, particularly when meaningful names are used. The benefits of using enumerations include: Reduces errors caused by transposing or mistyping numbers. Makes it easy to change values in the future.

What is an enumerator in programming?

In computer programming, an enumerated type (also called enumeration, enum, or factor in the R programming language, and a categorical variable in statistics) is a data type consisting of a set of named values called elements, members, enumeral, or enumerators of the type.

What is enum in JavaScript w3schools?

An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables). To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a comma. Note that they should be in uppercase letters.


2 Answers

You could also try to do something like this:

function Enum(values){
    for( var i = 0; i < values.length; ++i ){
        this[values[i]] = i;
    }
    return this;
}
var config = {};
config.type = new Enum(["RED","GREEN","BLUE"]);
// check it: alert( config.type.RED );

or even using the arguments parameter, you can do away with the array altogether:

function Enum(){
    for( var i = 0; i < arguments.length; ++i ){
        this[arguments[i]] = i;
    }
    return this;
}
var config = {};
config.type = new Enum("RED","GREEN","BLUE");
// check it: alert( config.type.RED );
like image 51
Locksfree Avatar answered Oct 10 '22 23:10

Locksfree


Just use an array:

var config.type =  ["RED", "BLUE", "YELLO"];

config.type[0]; //"RED"
like image 37
Naftali Avatar answered Oct 10 '22 21:10

Naftali