我有这个对象/数组的东西:
var states = {};
states["CA"] = new State("CA", "California");
states["AR"] = new State("AR", "Arizona");
....
如何检查是否已设置states["AL"]
?以下是否适用(在所有浏览器中)?
if (states["AL"] == undefined)
alert("Invalid state");
答案 0 :(得分:6)
推荐:
if (typeof states["AL"] == 'undefined')
alert("Invalid state");
Litteral undefined
是可能的,并且大部分时间都可以使用,但不会在某些浏览器中使用(IE mac,也许是其他浏览器)。
答案 1 :(得分:3)
您根本不需要进行字面比较;以下工作会很好......
if(states["AL"])
alert("State exists");
else
alert("State does not exist");
答案 2 :(得分:1)
或者,您可以说if ("AL" in states) { ... }
。
答案 3 :(得分:0)
function State(ab, name){
if(states && states[ab])return states[ab];
this.ab=ab;
this.name=name;
//whatever else, no return;
}