为什么 if([]) 被验证而 [] == false 在javascript中?

2022-01-19 00:00:00 boolean javascript
if([] == false) alert('empty array is false');
alert(+[]) // alert 0
if([]) alert('empty array is true');

他们都会运行警报

演示

推荐答案

这里的两个答案都是正确的,但我想根据 语言规范.出现明显矛盾结果的原因是 if 语句和相等比较的评估方式不同.

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.

if(expression) 语句的情况下,expression 被求值,然后转换为布尔类型(§ 12.5).数组是对象,当一个对象被转换为布尔值时,结果总是true (§ 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.比较可能需要多次类型转换,直到两个操作数都是相同的类型.操作数的顺序也很重要.根据那个算法,我们可以看到比较 [] == false 实际上是一个四步操作:

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:

  1. 其中涉及到一个布尔值,因此首先将其转换为数字(算法的第 7 步).于是就变成了:

  1. There is a Boolean involved, so it's converted to a Number first (step 7 of the algorithm). So it becomes:

[] == 0

  • 然后将数组转换为其原始值(参见 § 9.1 和§ 8.12.8),并变成一个空字符串(步骤 9).所以:

  • 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.
  • 相关文章