[英]How to check if a variable is set in Javascript?
I have this object/array thing: 我有这个对象/数组的东西:
var states = {};
states["CA"] = new State("CA", "California");
states["AR"] = new State("AR", "Arizona");
....
How can I check if states["AL"]
has been set or not? 如何检查是否已设置
states["AL"]
? Will the following work (in all browsers)? 以下功能(在所有浏览器中)都能工作吗?
if (states["AL"] == undefined)
alert("Invalid state");
Recommended: 推荐的:
if (typeof states["AL"] == 'undefined')
alert("Invalid state");
Litteral undefined
is possible and will work most of the time, but won't in some browser (IE mac, maybe others). 乱七八糟的
undefined
是可能的,并且在大多数情况下都可以使用,但是在某些浏览器(IE mac,也许是其他浏览器)中不会。
You don't have to do a literal comparison at all; 您根本不需要进行字面比较。 the following will work just fine...
以下将正常工作...
if(states["AL"])
alert("State exists");
else
alert("State does not exist");
或者,您可以说if ("AL" in states) { ... }
。
function State(ab, name){
if(states && states[ab])return states[ab];
this.ab=ab;
this.name=name;
//whatever else, no return;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.