简体   繁体   English

两个javascript对象如何在同一时间相等且不相等?

[英]How can two javascript objects be equal and not equal at the same time?

Below is an example comparing two JavaScript objects but I am confused by the returned values. 下面是一个比较两个JavaScript对象的示例,但我对返回的值感到困惑。

var i=new Object()
var j=new Object()

i==j false i==j

i!=j true i!=j是的

i>=j true i>=j是的

i<=j true i<=j

i>j false i>j

i<j false i<j false

How are the values determined for the above? 如何确定上述值? I am having trouble understanding. 我理解困难。

Here are the reasons, 原因如下,

i==j false //Since both are referring two different objects

i!=j True  //Since both are referring two different objects

i>=j true  //For this, the both objects will be converted to primitive first,
           //so i.ToPrimitive() >= j.ToPrimitive() which will be 
           //evaluated to "[object Object]" >= "[object Object]" 
           //That is why result here is true.

i<=j true  //Similar to >= case

i>j false  //Similar to >= case

i<j false  //Similar to >= case

i<-j false //similar to >= case but before comparing "[object object]" will be negated 
           //and will become NaN. Comparing anything with NaN will be false 
           //as per the abstract equality comparison algorithm 

You mentioned i<-j will be evaluated to true . 你提到i<-j将被评估为true But that is wrong, it will be evaluated to false . 但这是错误的,它将被评估为false See the reasons above. 看看上面的原因。

Because each time you create an object and assign it to a variable, the variable really has a reference to the new object. 因为每次创建对象并将其分配给变量时,变量实际上都有对新对象的引用。 The references are not the same so they are not equal. 引用不一样,所以它们不相等。 You can see this by doing this: 你可以这样做:

var a = {};
var b = a;

a == b

Not very enlightening but if you think references, it all makes sense. 不是很有启发性,但如果你认为参考,这一切都是有道理的。

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

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