防止 if 语句中的错误 "is undefined"

Prevent error "is undefined" in if statement

我的问题是关于更有效地防止 "variable is undefined" 错误。

例如

如果我使用下面的代码:

if (array[index] != undefined)
{
  if (array[index].id == 1)
  {
    // code 
  }
}

它将正常工作。但是,我可以使用

if (array[index] != undefined && array[index].id == 1)
{
 // code
}

没有得到 "variable is undefined" 错误,如果 array 未定义?

(我现在不能在我的代码中准确地测试这个,因为我正在构建一个客户端-服务器应用程序,我必须改变很多行来尝试它,所以我在这里问它。如有不妥请见谅)

是的,如果第一个条件失败,它将短路并忽略其他条件,就像在任何语言中一样。

&& will return true only if both the values of (a && b) a and b are truthy values.

如果第一个操作数 (expression) 被计算为 false,则第二个操作数 (expression) 根本不会被计算,因为结果总是 false

更好的做法是使用 typeof 来评估未定义的变量:

if ( typeof array[index] !== 'undefined' && array[index].id == 1)
{
   // code
}

记得检查字符串'undefined'不是原始值。

更多信息见MDN

不,如果数组未定义,您将需要一个如下所示的 if 语句:

if (array && array[index] !== undefined && array[index].id === 1) {
   // do things
}

第一个条件如果为假将停止所有其他条件的评估。唯一失败的方法是,如果你是 运行 你在严格模式下编码并且从未声明过 var array

仅当 if 括号内的所有条件都为真时,if 才会 return 为真。

如果表达式中的任何一个被评估为假,则整个表达式被评估为假。

如果您必须检查数组本身是否未定义,那么您还必须在那里检查数组类型。像这样:

if(typeof array !== 'undefined'){
    if ( typeof array[index] !== 'undefined' && array[index].id == 1)
    {
       // code
    }
}