How to check if a variable or object is undefined?

前端 未结 7 1561
Happy的楠姐
Happy的楠姐 2020-12-10 16:51

I always thought I could just check an undefined var by comparing it to undefined, but this is the error I get in the chrome console :

相关标签:
7条回答
  • 2020-12-10 17:30

    Process 1:

    if (jQuery) {  
        // jQuery is loaded  
    } else {
        // jQuery is not loaded
    }
    

    Process 2:

    if (typeof jQuery == 'undefined') {  
        // jQuery is not loaded  
    } else {
        // jQuery is loaded
    }
    
    0 讨论(0)
  • 2020-12-10 17:36

    if(jQuery) should be enough, shouldn't it?

    0 讨论(0)
  • 2020-12-10 17:38

    From here

    if(typeof jQuery == "undefined") { 
      document.write("undefined"); 
    }else{ 
       document.write("Exists"); 
    } 
    
    0 讨论(0)
  • 2020-12-10 17:46

    The variable called "jQuery" in your code has never been declared, so it will throw an error like "xxx(variable name) is not defined".

    You can use the typeof operator to check is a variable is undefined or not

    if (typeof(jQuery) == "undefined")
    
    0 讨论(0)
  • 2020-12-10 17:51

    You can use : if( typeof jQuery !== 'undefined')

    or

    Do what is recommended by mozilla

    if('jQuery' in window)

    https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/undefined

    0 讨论(0)
  • 2020-12-10 17:54

    There are several solutions:

    1. Use typeof. It is a special operator and will never result in a ReferenceError. It evaluates to "undefined" for, well, the undefined value or for a variable which does not exist in context. I'm not a fan of it, but it seems very common.

    2. Use window.jQuery. This forces a "property lookup": property lookups never fail, and return undefined if said property does not exist. I've seen it used in some frameworks. Has the downside of assuming a context (usually window).

    3. Make sure the variable is "declared": var jQuery; if (jQuery) { /* yay */ }. Doesn't seem very common, but it is entirely valid. Note that var is just an annotation and is hoisted. In the global context this will create the "jQuery" property.

    4. Catch the ReferenceError. Honestly, I have never seen this nor do I recommend it, but it would work.

    Happy coding.

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