【发布时间】:2017-11-20 20:26:27
【问题描述】:
我有两个日期变量:aankomst(到达)和 vertrek(出发)。我的目标是计算从抵达到离开的总住宿价格,这取决于淡季、中期和旺季。我认为我对如何实现这一点有一个很好的理论,并且到目前为止我制作的大部分脚本都可以正常工作。
最后的 for 循环是我失败的地方。在这一步,我想从 lowSeason、midSeason 或 peakSeason 的数组中找到当前日期,并将与该季节相关的成本价格添加到总价格中。这是代码,我添加了 cmets 以显示我尝试对每个步骤执行的操作,我还添加了大量警报,因此我确信在 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 年,但每个季节的开始日期和结束日期应该适用于所有年份,我该如何编辑这个?如果需要,我会在单独的问题中提出这个问题。
【问题讨论】:
-
您应该修改或删除您的original question。
-
您好,请问怎么办?我很乐意进行相应的编辑。
标签: javascript arrays loops date for-loop