更新时间:2022-02-19 23:11:35
如果你通过 =比较两个日期= ==
,比较两个日期对象的引用。表示相同日期的两个对象仍然是不同的对象。
If you compare two dates via ===
, you compare the references of the two date objects. Two objects that represent the same date still are different objects.
相反,比较来自 Date.prototype.getTime()$ c的时间戳$ c>:
function isDateInArray(needle, haystack) {
for (var i = 0; i < haystack.length; i++) {
if (needle.getTime() === haystack[i].getTime()) {
return true;
}
}
return false;
}
var dates = [
new Date('October 1, 2016 12:00:00 GMT+0000'),
new Date('October 2, 2016 12:00:00 GMT+0000'),
new Date('October 3, 2016 12:00:00 GMT+0000'),
new Date('October 2, 2016 12:00:00 GMT+0000')
];
var uniqueDates = [];
for (var i = 0; i < dates.length; i++) {
if (!isDateInArray(dates[i], uniqueDates)) {
uniqueDates.push(dates[i]);
}
}
console.log(uniqueDates);
优化和错误处理取决于你。
Optimization and error handling is up to you.