如何验证JavaScript中对象的存在?

以下工作:

if (!null)
   alert("GOT HERE");

但是这会抛出一个错误:

if (!maybeObject)
   alert("GOT HERE");

错误:

maybeObject没有定义。


当前回答

如果这是一个全局对象,你可以使用If (!window.maybeObject)

其他回答

我刚刚测试了上面的typeOf例子,没有一个适合我,所以我用了这个:

btnAdd = document.getElementById("elementNotLoadedYet"); if (btnAdd) { btnAdd。textContent = "Some text here"; }其他{ 警报(“没有发现!”); }

if (maybeObject !== undefined)
  alert("Got here!");

如果这是一个全局对象,你可以使用If (!window.maybeObject)

你可以安全地在未定义的变量上使用typeof操作符。

如果它被赋值,包括null, typeof将返回非undefined的值。Typeof总是返回一个字符串。

因此

if (typeof maybeObject != "undefined") {
   alert("GOT THERE");
}

我觉得这样最简单

if(myobject_or_myvar)
    alert('it exists');
else
   alert("what the hell you'll talking about");