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.
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.
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.
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.
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.
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 );
Just use an array:
var config.type = ["RED", "BLUE", "YELLO"];
config.type[0]; //"RED"
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