我觉得这应该生活在一个电码高尔夫球杆上,但以下行为引起了一个奇怪的错误,表面上看是无法理解的:
(a = new Date()) < (b = new Date())
a // Thu Feb 11 2016 12:24:19 GMT+0000 (GMT)
b // Thu Feb 11 2016 12:24:19 GMT+0000 (GMT)
a < b // false (correct)
a === b // false (incorrect) <<<
a > b // false (correct)
a <= b // true (correct)
a >= b // true (correct)** 编辑 **请问这些文件在哪里?
发布于 2016-02-11 12:38:00
除了=== 1之外,您的所有比较都是将日期强制限定为数字(它们的时间值,自纪元以来的毫秒),然后比较这些数字。===比较是检查a和b是否引用了同一个对象。(==也会做同样的事情。)
时间(在您的示例中)完全相同,但仍然有两个不同的对象。所以你所看到的结果。
附加说明:
// Create two Date instances, check if a's time value is less than b's
// (probably not, but it's just feasible this could cross a millisecond
// threshold)
(a = new Date()) < (b = new Date())
// Show the value of a and b
a // Thu Feb 11 2016 12:24:19 GMT+0000 (GMT)
b // Thu Feb 11 2016 12:24:19 GMT+0000 (GMT)
// See if a's time value is less than b's
a < b // false
// See if a and b refer to the same object (they don't)
a === b // false
// See if a's time value is greater than b's
a > b // false
// See if a's time value is less than or equal to b's
a <= b // true
// See if a's time value is greater than or equal to b's
a >= b 或者换个说法,您的代码基本上就是这样做的(请注意,+标志在哪里,而不是在哪里):
(a = new Date()) < (b = new Date())
a // Thu Feb 11 2016 12:24:19 GMT+0000 (GMT)
b // Thu Feb 11 2016 12:24:19 GMT+0000 (GMT)
+a < +b // false
a === b // false
+a > +b // false
+a <= +b // true
+a >= +b 请注意,如果时间是完全相同的,+a === +b (或+a == +b,或相当棘手- +a == b或a == +b)都将是真实的,因为我们将比较时间值。
为了好玩,下面是一个我们知道底层时间值完全相同的例子:
var a, b;
var now = Date.now(); // = +new Date(); on old browsers
show("create and compare: ", (a = new Date(now)) < (b = new Date(now)), "a's time is not < b's");
show("+a < +b: ", +a < +b, "a's time is not < b's");
show("a < b: ", a < b, "a's time is not < b's");
show("a === b: ", a === b, "a and b don't refer to the same object");
show("a == b: ", a == b, "a and b don't refer to the same object");
show("+a === +b: ", +a === +b, "their time values are the same");
show("+a == +b: ", +a == +b, "their time values are the same");
show("+a > +b: ", +a > +b, "a's time is not > b's");
show("a > b: ", a > b, "a's time is not > b's");
show("+a <= +b: ", +a <= +b, "a's time is equal to b's");
show("a <= b: ", a <= b, "a's time is equal to b's");
show("+a >= +b: ", +a >= +b, "a's time is equal to b's ");
show("a >= b: ", a >= b, "a's time is equal to b's ");
function show(prefix, result, because) {
var msg = prefix + result + ", " + because;
var pre = document.createElement('pre');
pre.innerHTML = msg.replace(/&/g, "&").replace(/</g, "<");
document.body.appendChild(pre);
}
发布于 2016-02-11 12:33:59
要比较日期,您需要使用.getTime()。因此,正确的比较应该是:
a.getTime() === b.getTime() //true
a.getTime() > b.getTime() //false
...https://stackoverflow.com/questions/35339355
复制相似问题