Avoozl
January 26, 2012, 1:16pm
1
Hello,
I am aware that I can delcare an enum in Javascript as follows
enum MyEnum {Value1=0, Value2=1};
However, I would like to declare an enum (or something similar) such that each value is associated with a string rather than an int, as follows:
enum MyEnum {Value1="hello", Value2="hello again"};
Any suggestions on ways to achieve something like this?
Thanks in advance.
tonyd
January 26, 2012, 3:32pm
2
Enums are always ints, but you can use them with strings like this:
enum Day {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}
var day = Day.Thursday;
if (day.ToString() == "Thursday")
print(day);
You can also do this:
if (day==Day.Thursday)
print(day);
What kind of work would you be doing with the values? Usually when I make enums, if I need a string associated with it I’d just use ToString, such that:
enum DamageTypes
{
Fire,
Water,
Earth,
Air
}
Then if I need to refer to those damage types for say, a menu, I’d just use “DamageTypes.Fire.ToString()” to get “Fire”
Does that help at all? Just naming the values of your enum as the strings you need?
What they said. If you really want the bidimensionality (whaat?) of your original attempt (key/string pairs) you should use a hashtable or dictionary .
Marrrk
January 26, 2012, 3:49pm
5
I would go with that was legend411 said, something like this:
enum MyEnum {Value1, Value2}
..
Dictionary<MyEnum, string> MyEnumStrings = new Dictionary<MyEnum, string>()
{
{ MyEnum.Value1, "hello"},
{ MyEnum.Value2, "hello again"}
};
string foo = MyEnumStrings[MyEnum.Value1];
you can also use System.Enum to convert strings back to enums. good for saving states of objects