两个JavaScript对象如何既相等又不相等?

4
下面是一个比较两个JavaScript对象的示例,但我对返回的值感到困惑。
var i=new Object()
var j=new Object()

i==j false

i!=j true

i>=j true

i<=j true

i>j false

i<j false

以上表格中的值是如何确定的?我理解起来有些困难。
2个回答

7
以下是原因:
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<-j将被评估为true。但是这是错误的,它将被评估为false。请参见上面的原因。

谢谢你的回答,我打错了,应该是'i<=j'而不是'i<-j'。由于'i<=j'为'true','i>=j'也为'true',所以i应该等于j,但不是。 - peng gao

0

因为每次创建一个对象并将其分配给变量时,变量实际上具有对新对象的引用。这些引用不相同,因此它们不相等。您可以通过执行以下操作来查看:

var a = {};
var b = a;

a == b

虽然不是很启发人,但如果你考虑引用,一切就都有意义了。


1
谢谢您的回答,我打错了符号,现在问题已经更新了。 - peng gao
@penggao,哪些不清楚?我的回答解释了除了<=>=之外的所有内容,我认为它们只是无关紧要的--在比较对象时没有好的答案,因此它们不具有逻辑性。编辑:刚意识到><也是同样的原因不合逻辑。 - Cymen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接