Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
160
rated 0 times [  162] [ 2]  / answers: 1 / hits: 16418  / 13 Years ago, tue, june 14, 2011, 12:00:00

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.


More From » javascript

 Answers
18

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

[#91714] Monday, June 13, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jonrened

Total Points: 627
Total Questions: 114
Total Answers: 99

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
jonrened questions
Mon, Nov 2, 20, 00:00, 4 Years ago
Tue, May 19, 20, 00:00, 4 Years ago
Tue, Jan 21, 20, 00:00, 4 Years ago
Thu, Nov 7, 19, 00:00, 5 Years ago
;