我们经常在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的一种(不必要的)行为,还是这两种方式之间真的有一些区别?


当前回答

这是一个非常罕见的例子,建议使用==而不是===。表达式somevar == null对于undefined和null将返回true,但对于其他所有内容将返回false(如果变量未声明则会出现错误)。

如预期的那样,使用!=将翻转结果。

现代编辑器不会对使用==或!=操作符加null发出警告,因为这几乎总是需要的行为。

最常见的比较:

undeffinedVar == null     // true
obj.undefinedProp == null // true
null == null              // true
0 == null                 // false
'0' == null               // false
'' == null                // false

自己试试吧:

let undefinedVar;
console.table([
    { test : undefinedVar,     result: undefinedVar     == null },
    { test : {}.undefinedProp, result: {}.undefinedProp == null },
    { test : null,             result: null             == null },
    { test : false,            result: false            == null },
    { test : 0,                result: 0                == null },
    { test : '',               result: ''               == null },
    { test : '0',              result: '0'              == null },
]);

其他回答

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

[undefined, null].includes(value)

这是唯一需要使用==和!=的情况:

if (val == null) console.log('val is null or undefined')
if (val != null) console.log('val is neither null nor undefined')

对于任何其他比较,应该使用严格比较符(===和!==)。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness https://2ality.com/2011/12/strict-equality-exemptions.html

使用Ramda,你可以简单地执行R.isNil(yourValue) Lodash和其他辅助库具有相同的功能。

使用严格比较运算符可以很容易地区分这两个值。

示例代码:

function compare(){
    var a = null; //variable assigned null value
    var b;  // undefined
    if (a === b){
        document.write("a and b have same datatype.");
    }
    else{
        document.write("a and b have different datatype.");
    }   
}

你必须区分不同的情况:

变量可以是未定义的或未声明的。如果在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