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? 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).
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");
Alternately, you could say 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;
}
精彩评论