为什么JavaScript中的[] ==![]为真? [英] Why is [] == ![] true in JavaScript?

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

问题描述

var arr = [];
Boolean(arr) // true
Boolean(!arr) // false
arr == arr // true
arr == !arr // true ??? what ???

我不想得到'推荐使用的答案=== 而不是 == '。
我想知道这种现象的原因以及JavaScript类型转换的原理。

I do not want to get the answer that 'recommend using === instead of =='. I would like to know the reason for this phenomenon and the principle of type conversion of JavaScript.

推荐答案

类型转换在JS中,特别是在松散的平等方面,是一个棘手的野兽。

Type conversion in JS, particularly with regards to loose equality, is a tricky beast.

在回答为什么这种特殊的松散平等以这种方式评估时总是开始的最佳位置请参阅这个按操作数类型比较的表格

The best place to always start when answering the question "why does this particular loose equality evaluate this way" is to consult this table of equality comparisons by operand type.

在这种情况下,我们可以看到,对于 [] == false ,操作数A是一个对象和操作数B是一个布尔值,因此执行的实际比较将是 ToPrimitive(A)== ToNumber(B)

In this case, we can see that for [] == false, Operand A is an Object and Operand B is a Boolean, so the actual comparison performed is going to be ToPrimitive(A) == ToNumber(B).

右边很简单; ToNumber(false)计算结果为 0 。完成并完成。

The right side of that is simple; ToNumber(false) evaluates to 0. Done and done.

左侧更复杂;您可以查看官方ECMAScript规范,了解 ToPrimitive的完整文档,但你真正需要知道的是,在这种情况下,它归结为 A.valueOf()。toString(),其中空数组的情况只是空字符串

The left side is more complex; you can check the official ECMAScript spec for full documentation of ToPrimitive, but all you really need to know is that in this case it boils down to A.valueOf().toString(), which in the case of the empty array is simply the empty string ""

因此,我们最终评估等式== 0 。字符串/数字 == 比较对字符串执行 ToNumber ToNumber( ) 0 ,所以我们得到 0 == 0 ,这当然是 true

So, we end up evaluating the equality "" == 0. A String/Number == comparison performs ToNumber on the string, and ToNumber("") is 0, so we get 0==0, which is of course true.

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

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