为什么 document.writeln("a" || "b") 输出的是 "a" 而不是 "true"?

6
为什么document.writeln("a" || "b")输出a而不是truedocument.writeln("a" && "b")输出b document.writeln(1==1 && 1!=1)输出false document.writeln(1!=1 && 'b')输出false document.writeln(1==1 && 'b')输出b 它是否计算内部内容并返回&&的最后一个值,以及||的第一个true值?

为什么会打印true?"a"是一个非空的、已定义的字符串,因此它是真值,因此它被返回给方法。另外1==1将被评估,最好使用1===1,这样不会将整数转换为字符串。 - mplungjan
2
我喜欢这种行为,说实话,之前甚至没有考虑过它。 - Paul Alan Taylor
2个回答

9
|| 和 && 并不总是返回布尔值。|| 会评估第一个参数,如果它评估为 true,则返回该参数;否则无条件返回第二个参数。
&& 会评估第一个参数,如果它评估为 true,则无条件返回第二个参数;否则返回第一个参数。
这使你能够做一些很棒的事情,比如:
function foo(optionalVar) {
    var x = optionalVar || 4; 
}
foo(10); //uses 10, since it is passed in;
foo(); //uses 4, the default value, since optionalVar=undefined, which is false

我第一次看到这个代码片段是在你提供的例子中。 - Shawn

2

它的运算顺序和真值表。

If(a OR b) : if a is true than the whole statement is true
If(a AND b): if a is true, doesnt mean that the statement is true, 
             but if b is true as well than the statement is true
|| is the same as OR
&& is the same as AND

更新
在函数式编程中,它会返回第一个 true 值。字符串被视为 true,因此它将返回该字符串。

Pointy 指出:
应该注意,空字符串不是 true。(也就是说,它是 false


1
需要注意的是,空字符串不是true(也就是说,它是false)。 - Pointy
修改了我的答案以更好地反映。 - Naftali

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接