如何验证JavaScript中对象的存在?
以下工作:
if (!null)
alert("GOT HERE");
但是这会抛出一个错误:
if (!maybeObject)
alert("GOT HERE");
错误:
maybeObject没有定义。
如何验证JavaScript中对象的存在?
以下工作:
if (!null)
alert("GOT HERE");
但是这会抛出一个错误:
if (!maybeObject)
alert("GOT HERE");
错误:
maybeObject没有定义。
当前回答
如果你只关心它的存在(它被宣布了吗?),认可的答案就足够了:
if (typeof maybeObject != "undefined") {
alert("GOT THERE");
}
如果你关心它的实际值,你应该添加:
if (typeof maybeObject != "undefined" && maybeObject != null ) {
alert("GOT THERE");
}
As typeof(null) == "object"
例如:bar = {x: 1, y: 2, z: null}
typeof( bar.z ) == "object"
typeof( bar.not_present ) == "undefined"
通过这种方式,您可以检查它既不是null也不是undefined,并且由于typeof在value不存在的情况下不会出错加上&&短路,因此您永远不会得到运行时错误。
就我个人而言,我建议在某个地方添加一个helper fn(让我们不要相信typeof()):
function exists(data){
data !== null && data !== undefined
}
if( exists( maybeObject ) ){
alert("Got here!");
}
其他回答
我觉得这样最简单
if(myobject_or_myvar)
alert('it exists');
else
alert("what the hell you'll talking about");
if (maybeObject !== undefined)
alert("Got here!");
我刚刚测试了上面的typeOf例子,没有一个适合我,所以我用了这个:
btnAdd = document.getElementById("elementNotLoadedYet"); if (btnAdd) { btnAdd。textContent = "Some text here"; }其他{ 警报(“没有发现!”); }
你可以安全地在未定义的变量上使用typeof操作符。
如果它被赋值,包括null, typeof将返回非undefined的值。Typeof总是返回一个字符串。
因此
if (typeof maybeObject != "undefined") {
alert("GOT THERE");
}
你可以用"typeof"。
if(typeof maybeObject != "undefined")
alert("GOT HERE");