【发布时间】:2018-08-02 14:17:55
【问题描述】:
我想创建一个包含唯一月份(2015 年 8 月、2015 年 9 月等)的数组。为此,我定义了以下函数,该函数将带有时间戳的对象作为键:
export function getUniqueMonths(exps) {
//1. get all keys from expenditures
const days = Object.keys(exps)
//2. convert key strings to timestamps
const daysInt = days.map((day) => (new Date(parseInt(day))))
//3. return only the "date portion" of the timestamp
const datePortion = daysInt.map((day) => (new Date(day.toDateString()) ))
//4. set each datePortion to 1st of month
const firstOfMonth = datePortion.map((day) => new Date(day.getFullYear(), day.getMonth(), 1) )
//5. keep only unique firstOfMonths
const uniqMonths = [...(new Set(firstOfMonth))]
return uniqMonths
}
然而,这个函数给了我一个这样的数组:
[Sat Aug 01 2015 00:00:00 GMT+0300 (Eastern European Summer Time), Sat Aug 01 2015 00:00:00 GMT+0300 (Eastern European Summer Time), Tue Sep 01 2015 00:00:00 GMT+0300 (Eastern European Summer Time), Sat Aug 01 2015 00:00:00 GMT+0300 (Eastern European Summer Time), Sat Aug 01 2015 00:00:00 GMT+0300 (Eastern European Summer Time), ...]
我认为获取时间戳的日期部分(第 3 步)并将所有日期设置为月初(第 4 步)就可以了。但是我的数组中仍然有重复项。
我错过了什么?
【问题讨论】:
-
集合使用相等来确定两个元素是否相同。日期是对象,所以相等性意味着它们必须是完全相同的日期对象,而不是引用同一时间点的两个不同的日期对象。您可以在创建 Set 之前将 Date 对象转换为字符串,然后再转换回来。
-
太棒了,只需在第 4 步中添加 .toString() 就可以了。谢谢!
标签: javascript reactjs ecmascript-6