[英]How can two javascript objects be equal and not equal at the same time?
下面是一个比较两个JavaScript对象的示例,但我对返回的值感到困惑。
var i=new Object()
var j=new Object()
i==j
假
i!=j
是的
i>=j
是的
i<=j
真
i>j
假
i<j
false
如何确定上述值? 我理解困难。
原因如下,
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
。 看看上面的原因。
因为每次创建对象并将其分配给变量时,变量实际上都有对新对象的引用。 引用不一样,所以它们不相等。 你可以这样做:
var a = {};
var b = a;
a == b
不是很有启发性,但如果你认为参考,这一切都是有道理的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.