This question already has answers here:
Why are two identical objects not equal to each other?
(7个答案)
5个月前关闭。
Example of the behaviour.
测试对象文字中的相等性时,
有人能够解释这种行为吗?
编辑:Ryan确实指出,通过NaN时,它将短路到11.9.3c中定义的
(7个答案)
5个月前关闭。
Example of the behaviour.
测试对象文字中的相等性时,
{} === {}
返回false([] === []
也是如此)。但是,如果编写函数以执行相同的测试并将对象文字作为参数传递,则比较将返回true。function foo(value) {
return value === value
}
foo({}) //Returns true!
有人能够解释这种行为吗?
最佳答案
对此的简单答案是因为表达式{} === {}
接受两个对象文字,而在函数foo
中则采用单数value
并将其与自身进行比较。实际上,foo
将始终返回true
(请参见编辑)。
更好的方法是:
const a = {}
const b = {}
console.log(a === b) // false, symmetric to {} === {}
console.log(a === a) // true, symmetric to (val) => val === val
编辑:Ryan确实指出,通过NaN时,它将短路到11.9.3c中定义的
false
。