javascript - 如何根据 Javascript 数组中的日期计算预订价格

标签 javascript arrays loops date for-loop

我有两个日期变量:aankomst(到达)和vertrek(出发)。我的目标是计算从抵达到离开的住宿总价格,这取决于淡季、中季和旺季。我认为我对如何实现这一目标有一个很好的理论,并且到目前为止我制作的大部分脚本都可以工作。

最后的 for 循环是我失败的地方。在这一步中,我想从数组中查找 lowSeason、midSeason 或 PeakSeason 的当前日期,并将与该季节相关的成本价格添加到总价格中。这是代码,我添加了注释来显示我在每个步骤中尝试执行的操作,并且我还添加了大量警报,因此我确信在 for 循环之前一切正常:

//fire function on load and  get the arrival date and departure date and make the array
window.onload = function getPrices() {
var aankomst = new Date();
var vertrek = new Date(aankomst.getTime() + (48 * 60 * 60 * 1000));
var maand = aankomst.getMonth();
var verblijfDagen = [];
var day = 1000*60*60*24;
var diff = (vertrek.getTime()- aankomst.getTime())/day;

//calculate all seperate days from arrival date to departure date and put them in an array   
for(var i=0;i<=diff; i++)
{
   var xx = aankomst.getTime()+day*i;
   var yy = new Date(xx);
   var zz = (yy.getDate()+"-"+(yy.getMonth()+1)+"-"+yy.getFullYear());
   var parts = zz.split('-');
   var zzDate = new Date(parts[2],parts[1]-1,parts[0]);
   //check if this date is in the correct Date structure
   alert(zzDate instanceof Date);
   verblijfDagen.push(zzDate)
}
//check if all the days are in the array
alert (verblijfDagen);

//declare the period of the different seasons and the daily cost rate during this season 
var peakSeason = {startDate: new Date(2017,10-1,01), endDate: new Date(2017,12-1,31), costRate: 500};
var midSeason = {startDate: new Date(2017,5-1,1), endDate: new Date(2017,9-1,30), costRate: 400};
var lowSeason = {startDate: new Date(2017,1-1,1), endDate: new Date(2017,4-1,30), costRate: 300};
var allSeasons = [peakSeason, midSeason, lowSeason]
//check if this date is in the correct Date structure
alert(lowSeason.startDate instanceof Date);
//check if the date is correct
alert (lowSeason.startDate);

//PROBLEM AREA check how many dates there are in the array and start the loop
var arrayLength = verblijfDagen.length;
for (var u = 0; u < arrayLength; u++) {
    //check if all dates of the array are looped
    alert(verblijfDagen[u]);
    //Iterate through allSeasons to find where the date belongs
    if (verblijfDagen[u] <= allSeasons.StartDate && allSeasons.verblijfDagen[u] >= endDate) {
    //Add costRate of this date to totalPrice
     var totalPrice = totalPrice + costRate;
    }
}
//return the total price
alert(totalPrice);
} 

问题:

  • 我在循环中犯了哪些错误以及如何修复它?
  • 在对象 lowSeason、midSeason 和 PeakSeason 中,我声明了 startDate 和 endDate 我声明了一年,所以它目前仅适用于 2017 年,但每个季节的开始日期和结束日期应该适用于所有年份,我该如何编辑这?如果需要,我会在单独的问题中提出这个问题。

最佳答案

您忘记在最后的循环中迭代每个季节。

但是有一个更好的方法来完成这一切:您不需要将每一天存储在数组中。您可以迭代季节,并通过简单的算术计算每个季节有多少天重叠。

在此代码中,函数接收三个参数:季节、到达日期和出发日期。该函数返回价格。

我以一个季节的抵达日期和下一季节的出发日期为例,因此最终价格为 400+500=900。

// Utility function to facilitate day counting without timezone issues:
const dayNumber = a => Date.UTC(a.getFullYear(), a.getMonth(), a.getDate()) / (24*60*60*1000);

function getPrices(allSeasons, arrival, departure) {
    return allSeasons.reduce( (totalPrice, {startDate, endDate, costRate}) => {
        let daysInSeason = Math.min(dayNumber(endDate) + 1, dayNumber(departure)) 
                         - Math.max(dayNumber(startDate),   dayNumber(arrival  ));
        return totalPrice + (daysInSeason > 0 && daysInSeason * 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}
    ],
    arrival = new Date(2017, 9-1,30),
    departure = new Date(arrival.getTime() + (48 * 60 * 60 * 1000)),
    totalPrice = getPrices(allSeasons, arrival, departure);

console.log(totalPrice);

关于javascript - 如何根据 Javascript 数组中的日期计算预订价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47400458/

相关文章:

javascript - array.push 不是函数

r - 使用循环在 R 中创建一个大列表

c++ - 访问 3 索引数组的最快方法

javascript - 我可以在 Web 项目上使用 binding.js 进行数据绑定(bind)吗?

Javascript 类的函数未定义

javascript - 使用 express 记录所有 GraphQL 响应

javascript - Momentjs/Angularjs - 检查 2 个日期是否在同一时期 - TimeSheet 项目

javascript - 如何在javascript中收集对象数组

c# - 迭代从 JSON 文件生成的动态对象的问题

javascript - 从外部调用立即执行函数