我在我们的应用程序中遇到了这段代码(已修改),并对它的工作方式感到困惑:
function someObject()
{
this.someProperty = {};
this.foo =
{
bar:
{
baz: function() { return "Huh?" }
}
};
this.getValue = function()
{
return (this.someProperty && this.foo.bar && this.foo.bar.baz && this.foo.bar.baz()) || null;
}
}
function test()
{
var o = new someObject();
var val = o.getValue();
alert(val);
}
Run Code Online (Sandbox Code Playgroud)
当你调用test()函数时,文字"嗯?" 警报.我不确定getValue的结果是如何返回的,我会认为做A && B && C && D会返回true,而不是D的值.
CMS*_*CMS 11
之所以会发生这种情况,是因为JavaScript中的布尔运算符可以返回操作数,而不一定是Boolean
结果,例如:
&&
如果第一个操作数是真值,则逻辑AND运算符()将返回第二个操作数的值:
true && "foo"; // "foo"
Run Code Online (Sandbox Code Playgroud)
并且它将返回第一个操作数的值,如果它本身是假的:
NaN && "anything"; // NaN
0 && "anything"; // 0
Run Code Online (Sandbox Code Playgroud)
这就是为什么在你的例子"Huh?"
中返回,因为所有前面的表达式都是真实的:
alert("A" && "B" && "C" && "Huh?"); // "Huh?"
alert(true && true && true && "Huh?"); // "Huh?"
Run Code Online (Sandbox Code Playgroud)
逻辑OR运算符(||
)具有类似的行为,如果第一个操作数是假的,它将返回第二个操作数的值:
false || "bar"; // "bar"
Run Code Online (Sandbox Code Playgroud)
并且它将返回第一个操作数的值,如果它本身是非虚假的:
"foo" || "anything"; // "foo"
Run Code Online (Sandbox Code Playgroud)
此行为通常用于设置默认值,例如:
function test (arg1) {
arg1 = arg1 || "default value";
}
Run Code Online (Sandbox Code Playgroud)
注意: Falsy值是那些胁迫到false
在布尔上下文中使用时,它们分别是:null
,undefined
,NaN
,0
,零长度的字符串,当然false
.其他任何东西都会强迫true
.