【发布时间】:2021-05-02 21:40:52
【问题描述】:
如果此范围内没有日期,如何在下面的代码中添加条件,它为 costRate 分配一个固定值?
function getPrices(allSeasons, checkin, checkout) {
const day = 1000*60*60*24;
return allSeasons.reduce( (totalPrice, season) => {
let daysInSeason = Math.round(
(Math.min(+season.endDate+day, checkout)
- Math.max(season.startDate, checkin)) / day);
return totalPrice + (daysInSeason > 0 && daysInSeason * season.costRate);
}, 0);
}
const allSeasons = [
{startDate: new Date(2017, 1-1, 1), endDate: new Date(2017, 4-1,30), costRate: 300},
{startDate: new Date(2017, 5-1, 1), endDate: new Date(2017, 9-1,30), costRate: 400},
{startDate: new Date(2017,10-1, 1), endDate: new Date(2017,12-1,31), costRate: 500}
],
checkin = new Date(2017, 9-1,30),
checkout = new Date(checkin.getTime() + (48 * 60 * 60 * 1000)),
totalPrice = getPrices(allSeasons, checkin, checkout);
console.log(totalPrice);
【问题讨论】:
-
一天中并不总是有 24 小时可以观察到夏令时,因此
day = 1000*60*60*24并不总是正确的,因此您需要处理它。 This answer 会有所帮助。
标签: javascript date math calendar reduce