Check if object exists in JavaScript

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

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

    0 讨论(0)
  • 2020-12-04 05:34
    if (maybeObject !== undefined)
      alert("Got here!");
    
    0 讨论(0)
  • 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");
    }
    
    0 讨论(0)
  • 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!"); 
    }
    
    0 讨论(0)
  • 2020-12-04 05:40

    Think it's easiest like this

    if(myobject_or_myvar)
        alert('it exists');
    else
       alert("what the hell you'll talking about");
    
    0 讨论(0)
  • 2020-12-04 05:41

    I used to just do a if(maybeObject) as the null check in my javascripts.

    if(maybeObject){
        alert("GOT HERE");
    }
    

    So only if maybeObject - is an object, the alert would be shown. I have an example in my site.

    https://sites.google.com/site/javaerrorsandsolutions/home/javascript-dynamic-checkboxes

    0 讨论(0)
提交回复
热议问题