Reputation: 35730
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.
Upvotes: 15
Views: 18312
Reputation: 2537
Define the Enum:
var type = {
RED: 1,
BLUE: 2,
YELLO: 3
};
get the color:
var myColor = type.BLUE;
Upvotes: 2
Reputation: 2702
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 );
Upvotes: 17
Reputation: 322502
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}
Upvotes: 1
Reputation: 360702
Use an array ([]
) instead of an object ({}
), then flip the array to swap keys/values.
Upvotes: 2
Reputation: 146310
Just use an array:
var config.type = ["RED", "BLUE", "YELLO"];
config.type[0]; //"RED"
Upvotes: 5