我们经常在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((someObject.someMember ?? null) === null) {
  // bladiebla
}

正在发生的事情非常清楚,很难被误解。这是非常重要的!: -)

这个使用??运营商(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator)。如果someObject的值。somember为空或未定义,则??运算符介入并将值置为空。

TBH,我喜欢这个东西的明确性,但我通常更喜欢someObject。somember == null,它更有可读性,熟练的JS开发人员可能知道这里发生了什么。

其他回答

测试空值(if (value == null))或非空值(if (value != null))比测试变量的定义状态更简洁。

此外,测试if(value)(或if(obj.property))以确保变量(或对象属性)存在失败,如果它定义为布尔值为false。买者自负。

在ES5或ES6中,如果你需要多次检查,你可以这样做:

Const excluded = [null, undefined, "]; if (! exclude .includes(varToCheck) { //它将不是null,不是undefined,不是void字符串 }

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

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

我认为最有效的测试“值为空或未定义”的方法是

if ( some_variable == null ){
  // some_variable is either null or undefined
}

所以这两条线是等价的

if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}
if ( some_variable != null ) {}

注1

正如问题中提到的,短变体要求some_variable已声明,否则将抛出ReferenceError。然而,在许多用例中,你可以假设这是安全的:

检查可选参数:

function(foo){
    if( foo == null ) {...}

检查现有对象上的属性

if(my_obj.foo == null) {...}

另一方面,typeof可以处理未声明的全局变量(只是返回未定义)。然而,正如Alsciende解释的那样,出于充分的理由,这些病例应该减少到最低限度。

注2

这个更短的变体是不等价的:

if ( !some_variable ) {
  // some_variable is either null, undefined, 0, NaN, false, or an empty string
}

so

if ( some_variable ) {
  // we don't get here if some_variable is null, undefined, 0, NaN, false, or ""
}

注3

一般情况下,建议使用===代替==。 建议的解决方案是这条规则的一个例外。为此,JSHint语法检查器甚至提供了eqnull选项。

jQuery风格指南:

严格的相等性检查(===)应该用于==。唯一的 异常是在检查undefined和null时通过null的方式。

// Check for both undefined and null values, for some important reason. 
undefOrNull == null;

2021 - 03年编辑:

现在大多数浏览器 支持null合并运算符(??) 和逻辑空赋值(??=),这允许更简洁的方式 如果变量为空或未定义,则指定一个默认值,例如:

if (a.speed == null) {
  // Set default if null or undefined
  a.speed = 42;
}

可以写成这些形式中的任何一种

a.speed ??= 42;
a.speed ?? a.speed = 42;
a.speed = a.speed ?? 42;

我用过这个方法

将id保存在某个变量中

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

然后使用if条件

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