简体   繁体   English

如果[]是[]而Array.prototype是[]为什么不([] == Array.prototype)

[英]If [] is [] and Array.prototype is [] why doesn't ([] == Array.prototype)

I'm messing around in console and saw the following: 我在控制台搞乱,看到以下内容:

>>> []
[]
>>> Array.prototype
[]
>>> [] == Array.prototype
false
>>> [] === Array.prototype
false

Can anyone explain this behavior? 谁能解释这种行为? (Sounds like a good candidate for wtfjs) (听起来像wtfjs的一个很好的候选人)

In Javascript, == on arrays is pointer equality, ie only true if the both arrays are the same object. 在Javascript中,== on数组是指针相等,即只有两个数组都是同一个对象才为真。 If arrays aren't pointer equal, then storing to one won't affect the other. 如果数组不是指针相等,那么存储到一个不会影响另一个。

>>> typeof [] == typeof Array.prototype
true

Essentially this is an extension of Raph Levien's answer but I could not fit it in a comment. 基本上这是Raph Levien答案的延伸,但我无法将其纳入评论。

I think it's illuminating to note that 我认为注意到这一点很有启发性

[] == [] || [] === [] //outputs false

Thus the fact that 因此,事实

[] == Array.prototype || [] === Array.prototype //outputs false

becomes expected. 变得预料。 Reading the MDN Comparison Operators yields the explanation as to why all four situations evaluate to false: 阅读MDN比较运算符可以解释为什么所有四种情况都评估为false:

  • Two objects are strictly equal if they refer to the same Object. 如果两个对象引用相同的对象,则它们严格相等。

Equal (==) - If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. Equal(==) - 如果两个操作数的类型不同,则JavaScript转换操作数,然后应用严格比较。 If either operand is a number or a boolean, the operands are converted to numbers if possible; 如果操作数是数字或布尔值,操作数将尽可能转换为数字; else if either operand is a string, the other operand is converted to a string if possible. 否则,如果任一操作数是字符串,则另一个操作数将转换为字符串(如果可能)。

Strict equal (===) - Returns true if the operands are strictly equal (see above) with no type conversion. 严格相等(===) - 如果操作数严格相等(见上文)且没有类型转换,则返回true。

js> []
[]
js> Array.prototype
[]
js> [].toString == Array.prototype.toString
true
js> [].toString === Array.prototype.toString
true

That is to say, the toString method of the objects is identical. 也就是说,对象的toString方法是相同的。 Of course, for Array.prototype.toString() (which is effectively what the second line is calling), the this object for the toString object contains no array-like properties, and hence gives [] . 当然,对于Array.prototype.toString()(实际上是第二行调用的),toString对象的this对象不包含类似数组的属性,因此给出了[]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM