Javascript test ( object && object !== “null” && object !== “undefined” )

后端 未结 9 2004
闹比i
闹比i 2020-12-29 22:46

I seem to be using this test a lot

if( object && object !== \"null\" && object !== \"undefined\" ){
    doSomething();
}

on

相关标签:
9条回答
  • 2020-12-29 23:12

    This should work without any issue.

    if(object){ // checks for null and undefined
        doSomething();
    }
    
    0 讨论(0)
  • 2020-12-29 23:14

    I don't think you can make that any simpler, but you could certainly refactor that logic into a function:

    function isRealValue(obj)
    {
     return obj && obj !== 'null' && obj !== 'undefined';
    }
    

    Then, at least your code becomes:

    if (isRealValue(yourObject))
    {
     doSomething();
    }
    
    0 讨论(0)
  • 2020-12-29 23:14

    I think you could simplify a bit your logic with the following:

    if (object != null && typeof(object) == "object") {
        doSomething();
    }
    

    The main problem is that if you just check typeof(object) == "object", it will return true if object is null since null's type is "object". However, if you first check that object != null, you can be sure you are having something that is neither undefined nor null.

    0 讨论(0)
  • 2020-12-29 23:15

    If object is truthy, we already know that it is not null or undefined (assuming that the string values are a mistake). I assume that a not null and not undefined test is wanted.

    If so, a simple comparison to null or undefined is to compare != null.

    if( object != null ){
        doSomething();
    }
    

    The doSomething function will run only if object is neither null nor undefined.

    0 讨论(0)
  • 2020-12-29 23:17

    maybe like this

       if (typeof object !== "undefined" || object !== null)
        // do something
    
    0 讨论(0)
  • 2020-12-29 23:26

    The best way to check if an object is empty is by using a utility function like the one below.

    create a function

    function isEmpty(obj) {
        for(var key in obj) {
            if(obj.hasOwnProperty(key))
                return false;
        }
        return true;
    }
    

    Use above function following way:-

    So if you have an empty object, you can check whether it is empty by using the above function.

    var myObj = {}; // Empty Object
    if(isEmpty(myObj)) {
        // Object is empty (Would return true in this example)
    } else {
        // Object is NOT empty
    }
    
    0 讨论(0)
提交回复
热议问题