开发者

How to check if a variable is set in JavaScript?

开发者 https://www.devze.com 2022-12-20 00:54 出处:网络
I have this object/array thing: var states = {}; states[\"CA\"] = new State(\"CA\", \"California\"); states[\"AR\"] = new State(\"开发者_如何转开发AR\", \"Arizona\");

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消