Check if object exists in JavaScript

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

    If you care about its existence only ( has it been declared ? ), the approved answer is enough :

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

    If you care about it having an actual value, you should add:

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

    As typeof( null ) == "object"

    e.g. bar = { x: 1, y: 2, z: null}

    typeof( bar.z ) == "object" 
    typeof( bar.not_present ) == "undefined" 
    

    this way you check that it's neither null or undefined, and since typeof does not error if value does not exist plus && short circuits, you will never get a run-time error.

    Personally, I'd suggest adding a helper fn somewhere (and let's not trust typeof() ):

    function exists(data){
       data !== null && data !== undefined
    }
    
    if( exists( maybeObject ) ){
        alert("Got here!"); 
    }
    

提交回复
热议问题