Javascript 如何根据日期计算预订价格
如何在下面的代码中添加条件如果此范围内没有日期,它会为成本率指定一个固定值Javascript 如何根据日期计算预订价格,javascript,date,math,calendar,reduce,Javascript,Date,Math,Calendar,Reduce,如何在下面的代码中添加条件如果此范围内没有日期,它会为成本率指定一个固定值 function getPrices(allSeasons, checkin, checkout) { const day = 1000*60*60*24; return allSeasons.reduce( (totalPrice, season) => { let daysInSeason = Math.round
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);
我很确定您可以用
daysinsteasure*(seasure.costRate | VALUE)
替换daysinsteasure*(seasure.costRate | VALUE)。如果season.costRate
不存在,它将用VALUE
替换它
罗布提出了一个很好的观点,我认为我的回答是错误的。您可能希望将其替换为totalPrice+(daysInSeason>0?daysInSeason*season.costRate:fixedValue)
一天中不一定有24小时可以使用日光节约,因此day=1000*60*60*24
并不总是正确的,因此您需要处理这个问题。会有帮助的。OP上说“如果这个范围内没有日期”,我想这意味着如果daysInSeason为零,那么它应该像totalPrice+(daysInSeason>0?daysInSeason*season.costRate:fixedValue)
。使用
可以防止负值并强制值为数字。是的,我认为你是对的。RobG!!此解决方案可行,但问题是,如果日期范围介于成本率和固定值之间,则不会计算平均值。