4

考虑以下嵌套数据结构:

var options = {
    option1 = {
        option1a : "foo",
        option1b : "bar"
    },
    option2 = {},
}

我有一个类似于上面的数据结构,我将其用作函数输入的可选参数列表。由于所有这些都是可选输入,因此它可能存在也可能不存在。最初,我使用typeof x == "undefined"语句链来确保例如 、optionsoption1都已option1a定义。我的代码最终看起来像这样定义一个变量:

if(typeof option != "undefined" 
  && typeof option.option1 != "undefined" 
  && typeof option.option1.option1a != "undefined){
    var x = option.option1.option1a;
} else {
    var x = "default";
};

我注意到我可以将其缩短为以下内容:

var x = option && option.option1 && option.option1.option1a || "default";

是否&&始终如一地返回最后一个真或第一个假陈述?并且是否||始终如一地返回第一个真实的陈述?逻辑会规定它们可以在某些实现中返回布尔值,但我对浏览器 / javascript 实现知之甚少,无法明确做出该声明。这是一种安全的方法吗,还是有更好的方法?

4

1 回答 1

9

是的,这将正常工作。&&返回最后一个 true 语句或第一个 false 语句,||返回第一个 true 语句或最后一个 false 语句。

var a = false || 0 // a === 0
var b = false && 0 // b === false
var c = true || 1 // c === true
var d = true && 1 // d === 1

并且在so&&之前被评估||

var e = false || 0 && null // e === null
var f = 1 || 2 && 3 // f === 1

还值得一提的是,虚假值包含的不仅仅是 JS 中的 undefined,因此您的 2 次检查并不完全相同。例如,值 0 将被认为是虚假的,即使它是“定义的”

有关详细的逻辑规范,请参见此处的官方规范。

句法

LogicalANDExpression :
BitwiseORExpression
LogicalANDExpression && BitwiseORExpression
LogicalANDExpressionNoIn :
BitwiseORExpressionNoIn
LogicalANDExpressionNoIn && BitwiseORExpressionNoIn
LogicalORExpression :
LogicalANDExpression
LogicalORExpression || LogicalANDExpression
LogicalORExpressionNoIn :
LogicalANDExpressionNoIn
LogicalORExpressionNoIn || LogicalANDExpressionNoIn

语义

The production LogicalANDExpression : LogicalANDExpression && BitwiseORExpression is evaluated as follows:
Let lref be the result of evaluating LogicalANDExpression.
Let lval be GetValue(lref).
If ToBoolean(lval) is false, return lval.
Let rref be the result of evaluating BitwiseORExpression.
Return GetValue(rref).
The production LogicalORExpression : LogicalORExpression || LogicalANDExpression is evaluated as follows:
Let lref be the result of evaluating LogicalORExpression.
Let lval be GetValue(lref).
If ToBoolean(lval) is true, return lval.
Let rref be the result of evaluating LogicalANDExpression.
Return GetValue(rref).
The LogicalANDExpressionNoIn and LogicalORExpressionNoIn productions are evaluated in the same manner as the LogicalANDExpression and LogicalORExpression productions except that the contained LogicalANDExpressionNoIn, BitwiseORExpressionNoIn and LogicalORExpressionNoIn are evaluated instead of the contained LogicalANDExpression, BitwiseORExpression and LogicalORExpression, respectively.
**NOTE** The value produced by a && or || operator is not necessarily of type Boolean. The value produced will always be the value of one of the two operand expressions.
于 2013-08-28T16:05:11.887 回答