How can I determine if a variable is 'undefined' or 'null'?

前端 未结 30 1482
耶瑟儿~
耶瑟儿~ 2020-11-22 03:30

How do I determine if variable is undefined or null?

My code is as follows:

var EmpN         


        
相关标签:
30条回答
  • 2020-11-22 04:10

    I've just had this problem i.e. checking if an object is null.
    I simply use this:

    if (object) {
        // Your code
    }
    

    For example:

    if (document.getElementById("enterJob")) {
        document.getElementById("enterJob").className += ' current';
    }
    
    0 讨论(0)
  • 2020-11-22 04:10
    (null == undefined)  // true
    
    (null === undefined) // false
    

    Because === checks for both the type and value. Type of both are different but value is the same.

    0 讨论(0)
  • 2020-11-22 04:11

    Calling typeof null returns a value of “object”, as the special value null is considered to be an empty object reference. Safari through version 5 and Chrome through version 7 have a quirk where calling typeof on a regular expression returns “function” while all other browsers return “object”.

    0 讨论(0)
  • 2020-11-22 04:13
    if (variable == null) {
        // Do stuff, will only match null or undefined, this won't match false
    }
    
    0 讨论(0)
  • 2020-11-22 04:13

    if you create a function to check it:

    export function isEmpty (v) {
     if (typeof v === "undefined") {
       return true;
     }
     if (v === null) {
       return true;
     }
     if (typeof v === "object" && Object.keys(v).length === 0) {
       return true;
     }
    
     if (Array.isArray(v) && v.length === 0) {
       return true;
     }
    
     if (typeof v === "string" && v.trim().length === 0) {
       return true;
     }
    
    return false;
    }
    
    0 讨论(0)
  • var i;
    
    if (i === null || typeof i === 'undefined') {
        console.log(i, 'i is undefined or null')
    }
    else {
        console.log(i, 'i has some value')
    }
    
    0 讨论(0)
提交回复
热议问题