Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何根据日期计算预订价格_Javascript_Date_Math_Calendar_Reduce - Fatal编程技术网

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!!此解决方案可行,但问题是,如果日期范围介于成本率和固定值之间,则不会计算平均值。