下面是一个比较两个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
如何确定上述值?我无法理解。
答案 0 :(得分: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
。看看上面的原因。
答案 1 :(得分:0)
因为每次创建对象并将其分配给变量时,该变量才真正具有对新对象的引用。引用不一样,所以它们不相等。你可以这样做:
var a = {};
var b = a;
a == b
不是很有启发性,但如果你认为参考,那一切都是有道理的。