如何修改getAllDaysInMonth函数以获取指定年份全年所有日期?
获取指定年份全年所有日期的解决方案
你可以基于现有的getAllDaysInMonth函数,封装一个新函数遍历全年12个月份(注意JavaScript的Date对象中月份是0起始的:1月对应0,12月对应11),把每个月的日期数组合并成一个全年的日期集合。
修改后的完整代码
function getAllDaysInMonth(year, month) { const date = new Date(year, month, 1); const dates = []; while (date.getMonth() === month) { dates.push(new Date(date)); date.setDate(date.getDate() + 1); } return dates; } function getAllDaysInYear(year) { let allDays = []; // 循环0到11,覆盖全年12个月份 for (let month = 0; month < 12; month++) { const monthDays = getAllDaysInMonth(year, month); allDays = [...allDays, ...monthDays]; // 也可以用concat方法:allDays = allDays.concat(monthDays); } return allDays; }
用法示例
// 获取2024年全年所有日期 const year2024Days = getAllDaysInYear(2024); // 输出2024年1月1日 console.log(year2024Days[0]); // 输出2024年12月31日 console.log(year2024Days[year2024Days.length - 1]);
补充说明
- 原函数
getAllDaysInMonth返回的是Date对象数组,每个元素都是对应日期的副本,避免了后续修改原对象导致的日期错乱问题 - 新函数
getAllDaysInYear通过12次循环调用原函数,将每个月的日期数组合并,最终返回全年的日期集合,完全适配你做日历式里程追踪的需求
内容的提问来源于stack exchange,提问作者samiel
相关产品推荐
相关产品推荐

