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

后端 未结 9 2010
闹比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: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
    }
    

提交回复
热议问题