我们经常在JavaScript代码中使用以下代码模式

if (typeof(some_variable) != 'undefined' && some_variable != null)
{
    // Do something with some_variable
}

是否有一种不那么冗长的检查方法具有相同的效果?

根据一些论坛和文献,简单地说下面应该有同样的效果。

if (some_variable)
{
    // Do something with some_variable
}

不幸的是,当some_variable未定义时,Firebug在运行时将这样的语句计算为错误,而第一个语句对它来说很好。这仅仅是Firebug的一种(不必要的)行为,还是这两种方式之间真的有一些区别?


当前回答

在ES5和ES6等较新的JavaScript标准中,你只需说

> Boolean(0) //false
> Boolean(null)  //false
> Boolean(undefined) //false

所有返回false,这类似于Python检查空变量。 所以如果你想写一个变量的条件逻辑,就说

if (Boolean(myvar)){
   // Do something
}

这里“null”或“空字符串”或“undefined”将被有效地处理。

其他回答

您可以使用lodash库。

_.isNil(value)对于null和undefined都给出true

测试地址:https://bazinga.tools/lodash

你可以检查变量是否有值。的含义,

if( myVariable ) {
//mayVariable is not :
//null
//undefined
//NaN
//empty string ("")
//0
//false

}

如果您不知道一个变量是否存在(也就是说,它是否声明过),您应该使用typeof操作符进行检查。如。

if( typeof myVariable !== 'undefined' ) {
    // myVariable will get resolved and it is defined
}

你必须区分不同的情况:

变量可以是未定义的或未声明的。如果在typeof以外的任何上下文中访问未声明的变量,将会得到一个错误。

if(typeof someUndeclaredVar == whatever) // works
if(someUndeclaredVar) // throws error

已声明但未初始化的变量是未定义的。

let foo;
if (foo) //evaluates to false because foo === undefined

Undefined properties , like someExistingObj.someUndefProperty. An undefined property doesn't yield an error and simply returns undefined, which, when converted to a boolean, evaluates to false. So, if you don't care about 0 and false, using if(obj.undefProp) is ok. There's a common idiom based on this fact: value = obj.prop || defaultValue which means "if obj has the property prop, assign it to value, otherwise assign the default value defautValue". Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the in operator instead value = ('prop' in obj) ? obj.prop : defaultValue

类似于你所做的,你可以这样做

If (some_variable === undefined || some_variable === null) { 做的东西 }

下面是另一种使用Array includes()方法的方法:

[undefined, null].includes(value)