为什么JavaScript比较运算符在数学上不一致? [英] Why are Javascript comparison operators mathematically inconsistent?
问题描述
a == b 如果且仅当
strong> a< = b和b <= a。
Javascript似乎不这么认为:
>新日期(400)< =新日期(400)
true
>新日期(400)> =新日期(400)
true
>新日期(400)==新日期(400)
false
有人可以解释导致这种结果的强制规则?似乎等于运算符 ==
的模糊应该相信两个 Date
s具有相等的值。
首先让我们从比较起点开始:
typeof new Date(400)
object
Javascript对象使用方法 .valueOf()
来比较前两种情况下的值。一般对象不知道如何在默认情况下比较一个对象,并使用字符串[object Object]。日期(400)< =新日期(400)
($)
new Date(400).valueOf()< = new Date(400).valueOf()
$ p但是,最后一个操作是为对象定义不同的,它比较两个对象(不是上面的整数)是否具有相同的引用,它们不会同时作为两个对象他们分别创建新对象。
400< = 400
true
新日期(400)==新日期(400)
false
如果您想以与前两个类似的方式比较日期值,您需要而是特别调用
.valueOf()
。新日期(400) .valueOf()== new Date(400).valueOf()
true
In a math class a long time ago I was taught that
a == b if and only if a <= b and b <= a.
Javascript doesn't seem to think so:
> new Date(400) <= new Date(400) true > new Date(400) >= new Date(400) true > new Date(400) == new Date(400) false
Can someone explain the type coercion rules that lead to this result? It seems that the fuzzy equal to operator
==
should believe that the twoDate
s have equal values.解决方案Firstly let's start with what you're comparing:
typeof new Date(400) "object"
Javascript objects use the method
.valueOf()
to compare the values in the first two cases. General objects don't know how to compare one to another by default and use the string "[object Object]". Dates on the other hand know how to.new Date(400) <= new Date(400) new Date(400).valueOf() <= new Date(400).valueOf() 400 <= 400 true
However, the last operation is defined for objects differently, it compares if the two objects (not the integers as above) have the same reference, which they won't as both of them are separately created new objects.
new Date(400) == new Date(400) false
If you want to compare the date values in a similar manner to your first two, you'll need to instead specifically call
.valueOf()
.new Date(400).valueOf() == new Date(400).valueOf() true
这篇关于为什么JavaScript比较运算符在数学上不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!