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

后端 未结 9 2015
闹比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: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();
    }
    

提交回复
热议问题