为什么 2 == [2] 在 JavaScript 中? [英] Why does 2 == [2] in JavaScript?
问题描述
我最近发现 JavaScript 中的 2 == [2]
.事实证明,这种怪癖有几个有趣的后果:
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
类似地,以下工作:
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?
推荐答案
您可以在 ECMA-spec 中查找比较算法(ECMA-262, 3rd edition 的相关部分针对您的问题:11.9.3, 9.1, 8.6.2.6).
You can look up the comparison algorithm in the ECMA-spec (relevant sections of ECMA-262, 3rd edition for your problem: 11.9.3, 9.1, 8.6.2.6).
如果将涉及的抽象算法翻译回 JS,则在评估 2 == [2]
时会发生什么基本上是这样的:
If you translate the involved abstract algorithms back to JS, what happens when evaluating 2 == [2]
is basically this:
2 === Number([2].valueOf().toString())
其中数组的 valueOf()
返回数组本身,单元素数组的字符串表示是单个元素的字符串表示.
where valueOf()
for arrays returns the array itself and the string-representation of a one-element array is the string representation of the single element.
这也解释了第三个例子,因为[[[[[[[2]]]]]]]].toString()
仍然只是字符串2
.
This also explains the third example as [[[[[[[2]]]]]]].toString()
is still just the string 2
.
如您所见,其中涉及到很多幕后魔法,这就是为什么我通常只使用严格相等运算符 ===
.
As you can see, there's quite a lot of behind-the-scene magic involved, which is why I generally only use the strict equality operator ===
.
第一个和第二个例子更容易理解,因为属性名称总是字符串,所以
The first and second example are easier to follow as property names are always strings, so
a[[2]]
相当于
a[[2].toString()]
这只是
a["2"]
请记住,在任何数组魔术发生之前,即使是数字键也被视为属性名称(即字符串).
Keep in mind that even numeric keys are treated as property names (ie strings) before any array-magic happens.
这篇关于为什么 2 == [2] 在 JavaScript 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!