Check if object exists in JavaScript

2019-01-12 15:21发布

How do I verify the existence of an object in JavaScript?

The following works:

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

But this throws an Error:

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

The Error:

maybeObject is not defined.

16条回答
Fickle 薄情
2楼-- · 2019-01-12 15:22
if (maybeObject !== undefined)
  alert("Got here!");
查看更多
乱世女痞
3楼-- · 2019-01-12 15:23

You can use:

if (typeof objectName == 'object') {
    //do something
}
查看更多
够拽才男人
4楼-- · 2019-01-12 15:28

You can use the ! operator twice !!:

if (!!maybeObject)
  alert("maybeObject exists");

Or one time ! for not exists:

if (!maybeObject)
  alert("maybeObject does not exist");

What is the !! (not not) operator in JavaScript?

查看更多
孤傲高冷的网名
5楼-- · 2019-01-12 15:30

You can safely use the typeof operator on undefined variables.

If it has been assigned any value, including null, typeof will return something other than undefined. typeof always returns a string.

Therefore

if (typeof maybeObject != "undefined") {
   alert("GOT THERE");
}
查看更多
Summer. ? 凉城
6楼-- · 2019-01-12 15:30

If that's a global object, you can use if (!window.maybeObject)

查看更多
啃猪蹄的小仙女
7楼-- · 2019-01-12 15:30

I've just tested the typeOf examples from above and none worked for me, so instead I've used this:

    btnAdd = document.getElementById("elementNotLoadedYet");
    if (btnAdd != null) {
       btnAdd.textContent = "Some text here";
    } else {
      alert("not detected!");
    }

查看更多
登录 后发表回答