JavaScript enumerator?

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.


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

Tags:

Javascript