Javascript 数组等于零但不等于本身 [英] Javascript array equal to zero but not itself
问题描述
我一直在 JavaScript 中使用数组,但无法弄清楚为什么会发生这种情况:
I've been playing around with arrays in JavaScript and cannot figure out why this happens:
console.log(0 == 0)
//true
console.log([] == 0)
//true
console.log(0 == [])
//true
console.log([] == [])
//false
console.log([] == ![])
// true
空数组左右都等于0,但为什么不等于自身?
The empty array is equal enough to zero both left and right, but why isn't it equal to itself?
我意识到比较两个对象不会导致 true
,但是如果比较,为什么它们会被强制为 0
(或错误,不应该是这种情况)将它们与 0
进行比较,而如果将它们与另一个数组进行比较,则会作为对象受到威胁?
I realise that comparing two objects would not result true
, but why are they coerced to 0
(or falsy, which shouldn't be the case) if you compare them to 0
, while threated as an object if you compare them to the other array?
推荐答案
由于一直没有给出完整的答案,现在我真的明白了,我会自己提供答案.
Since the complete answer is never given and I actually understand it now, I'll provide the answer myself.
我在 Ecma-262 pdf 中找到了这个:
I found this in the Ecma-262 pdf:
它基本上读到 [] == 0
与 Number([]) == 0
相同,后者与 0 == 0 相同
这是真的.这不适用于严格的 ===
.
It basically reads that [] == 0
is the same as Number([]) == 0
which is the same as 0 == 0
which is true. This does not apply to strict ===
.
除了第一条规则(x 与 y 相同
)之外,没有其他规则可以比较对象.这意味着一切都一样,内存地址也是如此.由于它们不共享相同的内存地址,因此适用规则 10(返回 false).
There is no rule to compare objects other then rule number one, which is x is the same as y
. This means the same in everything, also memory address. Since they are not sharing the same memory address, rule 10 applies (return false).
比较 x == y
,其中 x
和 y
是值,产生真或错误的.这样的比较执行如下:
The comparison
x == y
, wherex
andy
are values, produces true or false. Such a comparison is performed as follows:
如果
Type(x)
与Type(y)
相同,则
一个.返回执行严格相等比较的结果x === y
.
a. Return the result of performing Strict Equality Comparison x === y
.
如果 x
为 null
且 y
为 undefined
,则返回 true.
If x
is null
and y
is undefined
, return true.
这篇关于Javascript 数组等于零但不等于本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!