||将空字符串转换为bool,&&不是 [英] || converting empty string to bool, && not
问题描述
这正常吗?是功能还是错误? (我正在使用萤火虫):
Is this normal? Is it a feature or a bug? (I'm using firebug):
>>> '' || true
true
>>> '' || false
false
>>> '' && false
""
>>> '' && true
""
推荐答案
不将空字符串转换为Boolean
.
它正在评估左侧,其中一个空字符串为 falsy .然后,它检查右侧(因为它是或,而该侧可能为true),并返回该值.
It is evaluating the left hand side, of which an empty string is falsy. It then checks the right hand side (because it's an or, and that side may be true), and returns that value.
因为&&
需要将两面都设为 true ,而左侧是 falsy ,所以不必费心检查右侧(短路评估).因此,它只返回左侧,即空字符串.
Because &&
needs both sides to be true and the left hand side is falsy, it doesn't bother checking the right hand side (short circuit evaluation). Therefore, it just returns the left hand side, which is the empty string.
JavaScript始终返回其评估的最后一个值.
JavaScript always returns the last value it evaluated.
>>> '' || 0 || undefined || null || false || NaN || 'hello'
"hello"
这篇关于||将空字符串转换为bool,&&不是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!