我想定义一个具有连续整数值的常量列表,例如:
var config.type = {"RED": 0, "BLUE" : 1, "YELLO" : 2};
Run Code Online (Sandbox Code Playgroud)
但是"XX" : y每次我需要在其中添加新元素时添加一个很无聊.
所以我想知道是否有类似enumeratorC的东西所以我可以写:
var config.type = {"RED", "BLUE", "YELLO"}它们会自动给出唯一的整数值.
Loc*_*ree 15
你也可以尝试做这样的事情:
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 );
Run Code Online (Sandbox Code Playgroud)
甚至使用arguments参数,你可以完全取消数组:
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 );
Run Code Online (Sandbox Code Playgroud)
只需使用一个数组:
var config.type = ["RED", "BLUE", "YELLO"];
config.type[0]; //"RED"
Run Code Online (Sandbox Code Playgroud)