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

时间:2017-11-20 20:26:27

标签: javascript arrays loops date for-loop

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

最后的循环是我失败的地方。在该步骤中,我想在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年,但每个季节的开始日期和结束日期应该适用于所有年份,我该如何编辑?如果需要,我会在一个单独的问题中提出这个问题。

谢谢大家!

4 个答案:

答案 0 :(得分:3)

你忘了在最后一个循环中迭代每个季节。

但是有一种更好的方法可以做到这一切:你不需要每天都在一个阵列中存储。您可以在季节中进行迭代,并使用简单的算术计算每个季节与多少天的重叠。

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

我举例说明了一个季节到来的日期,以及下一个出发日期,所以最终价格是400 + 500 = 900。

&#13;
&#13;
function getPrices(allSeasons, aankomst, vertrek) {
    const day = 1000*60*60*24;
    return allSeasons.reduce( (totalPrice, season) => {
        let daysInSeason = Math.floor(
            (Math.min(+season.endDate+day, vertrek) 
             - Math.max(season.startDate, aankomst)) / 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}
    ],
    aankomst = new Date(2017, 9-1,30),
    vertrek = new Date(aankomst.getTime() + (48 * 60 * 60 * 1000)),
    totalPrice = getPrices(allSeasons, aankomst, vertrek);

console.log(totalPrice);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

  

我在循环中犯了什么错误,如何解决?

您应该在循环之前声明totalPrice变量并将其设置为零,这样您就可以在循环中累积价格。此外,allSeasons变量是一个对象数组,但您将其视为一个简单对象。因此,您可以解决此问题的方法是在第一个循环中执行第二个for循环以循环遍历allSeasons数组并比较日期。最后,<=>=在条件语句中混淆了。这是一个可能的解决方案:

var totalPrice = 0; for (var u = 0; u < verblijfDagen.length; u++) { for(var j = 0; j < allSeasons.length; j++) { if (verblijfDagen[u] >= allSeasons[j].startDate && verblijfDagen[u] <= allSeasons[j].endDate) { //Add costRate of this date to totalPrice totalPrice = totalPrice + allSeasons[j].costRate; } } }

答案 2 :(得分:1)

如果此范围内没有日期,如何在下面的代码中添加条件,为costRate分配一个固定值?

function getPrices(allSeasons, aankomst, vertrek) {
    const day = 1000*60*60*24;
    return allSeasons.reduce( (totalPrice, season) => {
        let daysInSeason = Math.floor(
            (Math.min(+season.endDate+day, vertrek) 
             - Math.max(season.startDate, aankomst)) / 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}
    ],
    aankomst = new Date(2017, 9-1,30),
    vertrek = new Date(aankomst.getTime() + (48 * 60 * 60 * 1000)),
    totalPrice = getPrices(allSeasons, aankomst, vertrek);

console.log(totalPrice);

答案 3 :(得分:0)

  

我在循环中犯了什么错误,我该如何解决?

您不应该使用var关键字增加,并且您在错误的范围内声明totalprice变量。将它移到for循环之外,可以根据需要访问它。您还应该尝试避免将变量名称分配给一个关闭值(如数组长度)

编辑:您似乎也混淆了>=<=

var totalPrice = 0;
for (var u = 0; u < verblijfDagen.length; u++) {       
    if (verblijfDagen[u] >= allSeasons.StartDate && allSeasons.verblijfDagen[u] <= endDate) {
     totalPrice += costRate;
    }
}
alert(totalPrice)
  

在对象lowSeason,midSeason和peakSeason中,我宣布startDate和endDate我宣布一年,所以它目前仅适用于2017年,但每个季节的开始日期和结束日期应该适用于所有年份,我该如何编辑此?

为此我会看一下moment.js。您可以为客户的开始和结束日期留出时间,并检查其月份值,如下所示:

var aankomst = moment();
var vertrek = moment(aankomst).add(2, 'days')

var month = aankomst.month(); //note this method considers january as 0 and december as 11
switch(month){
    case month >= 9 && month <= 11:
        //peakseason stuff 
        break;
    case month >= 4 && month <= 8:
        //midseason stuff
        break;
    case month >= 0 && month <= 3:
        //lowseason stuff
        break;
}

一般情况下,在JS中使用日期时,我建议每个人都使用时刻,这非常有帮助