Javascript Enumerator?
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...
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.
5 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 );
Just use an array:
var config.type = ["RED", "BLUE", "YELLO"];
config.type[0]; //"RED"
Use an array ([]) instead of an object ({}), then flip the array to swap keys/values.
I suppose you could make a function that accepts an Array:
function constants( arr ) {
for( var i = 0, len = arr.length, obj = {}; i < len; i++ ) {
obj[ arr[i] ] = i;
}
return obj;
}
var config.type = constants( ["RED", "BLUE", "YELLO"] );
console.log( config.type ); // {"RED": 0, "BLUE" : 1, "YELLO" : 2}
Or take the same function, and add it to Array.prototype.
Array.prototype.constants = function() {
for( var i = 0, len = this.length, obj = {}; i < len; i++ ) {
obj[ this[i] ] = i;
}
return obj;
}
var config.type = ["RED", "BLUE", "YELLO"].constants();
console.log( config.type ); // {"RED": 0, "BLUE" : 1, "YELLO" : 2}
Define the Enum:
var type = {
RED: 1,
BLUE: 2,
YELLO: 3
};
get the color:
var myColor = type.BLUE;