简体   繁体   English

测试JavaScript关联数组中是否存在枚举值

[英]Testing for existence of enumeration value in a JavaScript associative array

I have built an "enumeration" in javascript using the following syntax: 我使用以下语法在javascript中构建了“枚举”:

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. 我想存储一个包含0个或多个这些枚举值的字典,并且我希望能够测试字典中是否存在任何特定值。 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. 我可以使下拉列表正常工作,但是无法测试字典中是否存在for(在MyEnum中为x)字段之外的字典。 If I use: 如果我使用:

list[MyEnum.MY_VAL_1]

I always get false (I guess because the items are stored without the MyEnum namespace?). 我总是错误的(我想是因为项目存储时没有MyEnum名称空间?)。 If I try: 如果我尝试:

list[MY_VAL_1]

I just get an Uncaught ReferenceError. 我刚收到一个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/ 这是到目前为止我所做的事情的jsFiddle: http : //jsfiddle.net/jKfbh/3/

MyEnum.MY_VAL_1 returns the object you specified, { name: "Value 1" } . MyEnum.MY_VAL_1返回您指定的对象{ 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. JavaScript没有枚举。 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. 在ES5中,您可以将属性定义为密封冻结等,从而使它们的性能类似于枚举,但是,老实说,如果您发现自己需要JavaScript中的这种功能,则可能需要重新考虑设计。 This doesn't mean that your design is necessarily bad, it's that JavaScript provides almost no instrumentation to do what you want. 这并不意味着您的设计一定很糟糕,而是JavaScript几乎不提供执行所需功能的工具。

you can check the value like this: 您可以像这样检查值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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