【发布时间】:2019-12-27 13:01:33
【问题描述】:
我试图弄清楚如何订购一个包含 Date 对象的数组。
下面是我的数组Appointment[](包含3个对象)
0: {id: 36, appointmentDate: "2019-12-27T10:28:15"}
1: {id: 57, appointmentDate: "2020-01-03T08:29:25"}
2: {id: 58, appointmentDate: "2020-01-15T15:45:19"}
这是我尝试实施但没有奏效的方法
a.appointmentDate.getTime is not a function
if(param === 'a'){
return value.sort((a, b) => { return a.appointmentDate.getTime() - b.appointmentDate.getTime() });
}
下面说另一种方法也不起作用
The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type
if(param === 'a'){
return value.sort((a, b) => { return new Date(a.appointmentDate) - new Date(b.appointmentDate});
}
【问题讨论】:
-
直接使用字符串排序:
a.appointmentDate.localeCompare(b.appointmentDate)。如果要使用 Date 构造函数,请在日期对象前添加+:+new Date(a.appointmentDate)。打字稿不喜欢减去日期和类型强制 -
第一个抛出错误,因为
appointmentDate是一个字符串而不是Date。第二个错误来自 TypeScript,因为它不允许对Date对象进行-操作。如果有返回日期数字表示的方法/属性,只需检查Date的文档即可。
标签: javascript angular sorting