Why does 2 == [2] in JavaScript?

2020-01-24 10:06发布

I recently discovered that 2 == [2] in JavaScript. As it turns out, this quirk has a couple of interesting consequences:

var a = [0, 1, 2, 3];
a[[2]] === a[2]; // this is true

Similarly, the following works:

var a = { "abc" : 1 };
a[["abc"]] === a["abc"]; // this is also true

Even stranger still, this works as well:

[[[[[[[2]]]]]]] == 2; // this is true too! WTF?

These behaviors seem consistent across all browsers.

Any idea why this is a language feature?

Here are more insane consequences of this "feature":

[0] == false // true
if ([0]) { /* executes */ } // [0] is both true and false!

var a = [0];
a == a // true
a == !a // also true, WTF?

These examples were found by jimbojw http://jimbojw.com fame as well as walkingeyerobot.

9条回答
beautiful°
2楼-- · 2020-01-24 11:07

It is because of the implicit type conversion of == operator.

[2] is converted to Number is 2 when compared with a Number. Try the unary + operator on [2].

> +[2]
2
查看更多
乱世女痞
3楼-- · 2020-01-24 11:08
[0] == false // true
if ([0]) { /* executes */ } // [0] is both true and false!

That's interesting, it's not that [0] is both true and false, actually

[0] == true // false

It is javascript's funny way of processing if() operator.

查看更多
Ridiculous、
4楼-- · 2020-01-24 11:08

You are comparing 2 objects in every case.. Dont use ==, if you are thinking of comparison, you are having === in mind and not ==. == can often give insane effects. Look for the good parts in the language :)

查看更多
登录 后发表回答