简体   繁体   中英

Testing for existence of enumeration value in a JavaScript associative array

I have built an "enumeration" in javascript using the following syntax:

MyEnum = {
    MY_VAL_1 : { name: "Value 1" },
    MY_VAL_2 : { name: "Value 2" },
    MY_VAL_3 : { name: "Value 3" }
};

I want to store a dictionary containing 0 or more of these enumeration values and I want to be able to test for the existence of any particular value in the dictionary. I also want to show the values that are not in the dictionary inside a dropdown, and the values that are in the dictionary in another dropdown, and have buttons that allow the user to add or remove values to or from the dictionary using these dropdowns.

I can get the dropdowns working, but I can't test for existence in the dictionary outside of a "for (x in MyEnum)" block. If I use:

list[MyEnum.MY_VAL_1]

I always get false (I guess because the items are stored without the MyEnum namespace?). If I try:

list[MY_VAL_1]

I just get an Uncaught ReferenceError.

How can I get this to work, or is there a better way to do this?

Here is a jsFiddle of what I've done so far: http://jsfiddle.net/jKfbh/3/

MyEnum.MY_VAL_1 returns the object you specified, { name: "Value 1" } .

To test if a value is in your "list" (which, in fact, is an object or dictionary), you should use this code:

if (list["MY_VAL_1"]) {
    alert('val 1 is in list');
}
var MyEnum = {
MY_VAL_1 : { name: "Value 1" },
MY_VAL_2 : { name: "Value 2" },
MY_VAL_3 : { name: "Value 3" }
};
alert("MY_VAL_1" in MyEnum);

JavaScript doesn't have enums. In ES5 you could define properties as sealed frozen etc. which would make them perform similarly to enums, but, in all honesty, if you found yourself in need of such a feature in JavaScript, you probably need to reconsider your design. This doesn't mean that your design is necessarily bad, it's that JavaScript provides almost no instrumentation to do what you want.

you can check the value like this:

if(MyEnum['MY_VAL_1']){
    alert('val 1 in the list');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM