为什么`[] == false`为真,但只有`[]`的计算结果为真? [英] Why is `[] == false` is true but just `[]` evaluates to true?

查看:99
本文介绍了为什么`[] == false`为真,但只有`[]`的计算结果为真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下按预期打印'A',因为数据类型不同,因此数组被哄骗为原始形式,对于空数组, false

The following prints 'A' as expected, since the data type is different so the array is coaxed into a primitive form which is false for empty arrays.

if ([] == false)
    console.log('A');
else
    console.log('B');

但是为什么以下代码也打印'A'?

But then why the following code too prints 'A'?

if ([])
    console.log('A');
else
    console.log('B');


推荐答案


为什么 [] == false 为真

因为与原始值相比,数组行为奇怪。

Because arrays behave oddly when compared to primitive values.

特别是当你比较布尔值的任何非布尔值,布尔值作为数字处理。然后,当您将一个数字与一个对象进行比较时,该对象是转换为原始 - 其中< a href =http://es5.github.io/#x8.12.8 =nofollow>对数组进行字符串化,然后再将其与数字进行比较。现在,该字符串转换为数字,以便进行比较:

In particular, when you compare any non-boolean to a boolean, the boolean is handled as a number. Then, when you compare a number to an object the object is converted to a primitive - which stringifies the array before again comparing it to the number. Now, that string is converted to a number so that they can be compared:

[] == false
[] == 0
"" == 0
0 == 0

同样,你可以尝试

[1] == true
[1] == 1
"1" == 1
1 == 1

[2] == true
[2] == 1
"2" == 1
2 == 1




但只是 [] 评估为真?

因为任何对象都是真实的

这篇关于为什么`[] == false`为真,但只有`[]`的计算结果为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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