Check if object exists in JavaScript

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

    The thread was opened quite some time ago. I think in the meanwhile the usage of a ternary operator is the simplest option:

    maybeObject ? console.log(maybeObject.id) : ""
    

提交回复
热议问题