Check if object exists in JavaScript

前端 未结 18 2696
抹茶落季
抹茶落季 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:46

    Two ways.

    typeof for local variables

    You can test for a local object using typeof:

    if (typeof object !== "undefined") {}
    

    window for global variables

    You can test for a global object (one defined on the global scope) by inspecting the window object:

    if (window.FormData) {}
    

提交回复
热议问题