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

后端 未结 9 2050
闹比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条回答
  •  猫巷女王i
    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.

提交回复
热议问题