【问题标题】:How can two javascript objects be equal and not equal at the same time?两个javascript对象如何同时相等和不相等?
【发布时间】:2016-02-28 09:15:14
【问题描述】:

下面是一个比较两个 JavaScript 对象的示例,但我对返回的值感到困惑。

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

i==j

i!=j

i>=j

i<=j

i>j

i<j

上述值是如何确定的?我无法理解。

【问题讨论】:

    标签: javascript object


    【解决方案1】:

    原因如下,

    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 
    

    您提到i&lt;-j 将被评估为true。但这是错误的,它将被评估为false。见上述原因。

    【讨论】:

    • 谢谢你的回答,我打错了,应该是'i =j' 是 'true',所以我应该等于 j,但不是。
    【解决方案2】:

    因为每次创建对象并将其分配给变量时,该变量确实具有对新对象的引用。引用不相同,因此它们不相等。你可以这样做:

    var a = {};
    var b = a;
    
    a == b
    

    不是很有启发性,但如果您认为参考,这一切都是有道理的。

    【讨论】:

    • 感谢您的回答,我输入了错误的符号,现在问题已更新。
    • @penggao 哪些不清楚?我的回答解释了除了&lt;=&gt;= 之外的所有内容,我会说这些都是无关紧要的——在比较对象时没有很好的答案,因此它们不符合逻辑使用。编辑:刚刚意识到&gt;&lt; 但出于同样的原因不合逻辑。
    猜你喜欢
    • 2014-01-02
    • 1970-01-01
    • 2013-03-06
    • 2010-09-17
    • 2022-12-04
    相关资源
    最近更新 更多