javascript比较危机 [英] javascript comparison crises

查看:109
本文介绍了javascript比较危机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下问题,无法掌握原因,可以解释吗?

I came across the following and was unable to grasp the reason, can anyone explain please?

var foo = [0];
console.log(foo == !foo); // true 
console.log(foo == foo);  // true


推荐答案

第二个比较很容易解释: foo 等于它自己。

The second comparison is simple to explain: foo is equal to itself.

第一个,但是有点棘手: foo 是一个数组,它是一个对象,当 true /ecma-262/5.1/#sec-9rel =nofollow>强制为布尔值。因此!foo false 。但是比较左侧的 foo 未转换为布尔值。两个操作数实际上在等式比较期间转换为数字。这是它的评估方式:

The first one, however, is a bit tricky: foo is an array, which is an object, which evaluates to true when coerced to boolean. So !foo is false. But foo on the left side of the comparison is not being converted to boolean. Both operands are actually converted to numbers during the equality comparison. This is how it evaluates:

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

MDN ,与等于运算符<$ c的比较$ c> == :


如果两个操作数的类型不同,JavaScript会转换操作数然后应用严格的比较。如果任一操作数是数字或布尔值,操作数将转换为数字,如果可能的话

If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible

我知道这个解释听起来很肤浅。它实际上要复杂得多,但基本步骤是我上面列出的。您可以查看ECMA-262规范的详细信息,特别是 9 < a>和 11.9

I know this explanation sounds superficial. It's actually much more complicated than that, but the basic steps are the ones I listed above. You can see the details on the ECMA-262 specification, particularly on sections 9 and 11.9.

这篇关于javascript比较危机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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