为什么如果([])时,同时[]验证==在JavaScript假的? [英] Why if([]) is validated while [] == false in javascript?

查看:96
本文介绍了为什么如果([])时,同时[]验证==在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:


  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。

  • Now that we have two Numbers, the comparison evaluates to true according to step 1.c.iii.
  • 这篇关于为什么如果([])时,同时[]验证==在JavaScript假的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆