Check if object exists in JavaScript

前端 未结 18 2645
抹茶落季
抹茶落季 2020-12-04 05:26

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

The following works:

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

But this throws a

18条回答
  •  执笔经年
    2020-12-04 05:36

    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");
    }
    

提交回复
热议问题