今天我遇到了 Javascript 中的奇怪行为。下面是代码
return "" && false
返回“”。
为什么会这样?
最佳答案
因为
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).
这意味着:
Return the first value if it is falsy, return the second value if the first is truthy.
这也是您这样做时看到的行为:
return false && true
你得到 false
。
这也意味着这
return 23 && "Hello"
会给你“你好”
关于Javascript : Strange behaviour `empty string` AND `false` returns empty string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31984087/