为什么如果([])时,同时[]验证==在JavaScript假的? [英] Why if([]) is validated while [] == false in javascript?
问题描述
if([] == false) alert('empty array is false');
alert(+[]) // alert 0
if([]) alert('empty array is true');
它们都将运行警报
They both will run the alert
推荐答案
这里既有目前的答案是正确的,但我想补充基础上的语言规范。究其原因,看似矛盾的结果是,如果
语句和平等的比较是不同的评价。
Both current answers here are correct, but I'd like to add a more detalied explanation based on the language specification. The reason for the apparently contradictory outcomes is that if
statements and equality comparisons are evaluated differently.
在如果(例如pression)
语句的情况下,的前pression 的评估,然后转换为布尔型(§12.5 )。数组是对象,当一个对象被转换为布尔,结果总是真正
(第9.2 )。
In the case of an if(expression)
statement, the expression is evaluated and then converted to the boolean type (§ 12.5). Arrays are Objects, and when an Object is converted to Boolean, the result is always true
(§ 9.2).
与 ==
遵循一套不同的规则,对的第11.9.3 。比较可能需要多个类型转换,直到这两个操作数的类型相同。操作数的顺序也很重要。根据这一算法,我们可以看到比较 [] ==虚假
实际上是一个四步操作:
Equality comparisons with ==
follow a different set of rules, detailed on § 11.9.3. The comparison may require multiple type conversions, until both operands are the same type. The order of the operands is also important. According to that algorithm, we can see that the comparison [] == false
is actually a four-step operation:
-
有涉及一个布尔值,所以它转换成一个数第一(算法的步骤7)。因此,它变成了:
There is a Boolean involved, so it's converted to a Number first (step 7 of the algorithm). So it becomes:
[] == 0
Then the array is converted to its primitive value (see § 9.1 and § 8.12.8), and becomes an empty string (step 9). So:
"" == 0
在一个字符串比较数值,字符串转换成数第一(第5步,下面就的第9.3.1 ):
0 == 0
真正
根据步骤1.c.iii。
true
according to step 1.c.iii.这篇关于为什么如果([])时,同时[]验证==在JavaScript假的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!