为什么两个if('0'== false)和if('0')在Javascript中评估为true? [英] why do both if('0'==false) and if('0') evaluate to true in Javascript?
问题描述
因此,据我所知,Javascript中的 if
语句将其条件的结果转换为布尔值,然后执行它,如下所示
So for what I know is that the if
statement in Javascript casts the result of its condition to a Boolean, and then executes it likes the following
if(true) {
// run this
}
if(false) {
// do not run this
}
这样可行。但如果我这样做:
And that works. But If I do this:
if('0' == false) {
// We get here, so '0' is a falsy value
}
然后我会期待这个
if('0') {
// We don't get here, because '0' is falsy value
}
但我得到了
if('0') {
// We *DO* get here, even though '0' is falsy value
}
那么发生了什么?显然,如果
没有检查它的条件是否是真值或假值,而是进行其他转换?
So what's happening? Apparently, if
does not check if its condition a truthy or falsy value, but does some other conversion?
推荐答案
这只是 <$ c $的陷阱之一c> == 规则相当复杂。
This is just one of those "gotchas" with the ==
rules which are rather complex.
比较x == y,其中x和y是值,产生true或false。这样的比较如下进行:
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
(4)如果Type(x)是Number而Type(y)是String,
返回结果比较x == ToNumber(y)。
(4) If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
(5)如果Type(x)是String而Type(y)是Number,
返回结果比较ToNumber(x)== y。
(5) If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
(6)如果Type(x)是布尔值,则返回比较结果ToNumber(x)== y。
(6) If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
(7)如果Type(y)是布尔值,则返回比较结果x == ToNumber(y)。
(7) If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
在这种情况下,这意味着'0'== false
首先被强制执行'0 '== 0
(按规则#7)然后在第二次传递时,它被强制转换为 0 == 0
(按规则# 5)结果为真。
In this case that means that '0' == false
is first coerced do '0' == 0
(by rule #7) and then on the second pass through, it is coerced to 0 == 0
(by rule #5) which results in true.
这个特殊情况有点棘手,因为 false~> 0
而不是'0'〜> true
(可能是预期的)。但是,'0'
本身就是一个真值,并且可以用上述规则解释行为。要在测试期间进行严格的truthy-falsey相等(不同于严格相等)而不在相等期间进行隐式转换,请考虑:
This particular case is somewhat tricky because of false ~> 0
instead of '0' ~> true
(as what might be expected). However, '0'
is itself a truth-y value and the behavior can be explained with the above rules. To have strict truthy-falsey equality in the test (which is different than a strict-equality) without implicit conversions during the equality, consider:
!!'0' == !!false
(对于所有值:!falsey - > true
和!truthy - > false
。)
这篇关于为什么两个if('0'== false)和if('0')在Javascript中评估为true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!