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


当前回答

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

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

其他回答

为了理解,让我们分析一下Javascript引擎在转换undefined、null和”(也是一个空字符串)时返回的值是什么。您可以直接在开发人员控制台检查相同的内容。

你可以看到所有都被转换为false,这意味着所有这三个都是通过javascript假设“缺乏存在”。因此,您不需要像下面这样显式地检查代码中的所有三个。

if (a === undefined || a === null || a==='') {
    console.log("Nothing");
} else {
    console.log("Something");
}

我还想指出一件事。

布尔(0)的结果是什么?

当然是假的。当0是预期结果中的有效值时,这将在代码中创建一个错误。所以在写代码的时候一定要检查这个。

你必须定义一个这样的函数:

validate = function(some_variable){
    return(typeof(some_variable) != 'undefined' && some_variable != null)
}

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

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

我用过这个方法

将id保存在某个变量中

var someVariable = document.getElementById("someId");

然后使用if条件

if(someVariable === ""){
 //logic
} else if(someVariable !== ""){
 //logic
}

无论yyy是undefined还是null,它都会返回true

if (typeof yyy == 'undefined' || !yyy) {
    console.log('yes');
} else {
    console.log('no');
}

yes

if (!(typeof yyy == 'undefined' || !yyy)) {
    console.log('yes');
} else {
    console.log('no');
}

no