我是个菜鸟。如果这个问题很愚蠢的话,我很抱歉。我正在为旅行写一个脚本。我需要得到出发的开始日期和结束日期。返回的日期要得到开始/结束日期的偏移量;在调用函数后,出发日期也改变了。我不能理解我的错误。请帮助。
var departstart=getNextDayOfTheWeek(3,0);
console.log("Departure from " + departstart);
var departend=getNextDayOfTheWeek(3,0);
console.log("Departure to " + departend);
var returnstart=getoffday(3,departstart);
// check again depature
console.log("Departure from " + departstart);
// Has changed?!?!?!
console.log("Return from " + returnstart);
var returnend=getoffday(3,departstart);
console.log("Return to " + returnend);
// Gets a date of next day of the week
function getNextDayOfTheWeek(dayOfWeek, excludeToday = true, refDate = new Date()) {
refDate.setHours(0,0,0,0);
refDate.setDate(refDate.getDate() + +!!excludeToday +
(dayOfWeek + 7 - refDate.getDay() - +!!excludeToday) % 7);
return (refDate);
}
// Gets a date of diff day from given date
function getoffday(diff=0, workyday = new Date()) {
console.log("Inside function before execution " + workyday);
workyday.setHours(0,0,0,0);
workyday.setDate(workyday.getDate() + diff);
console.log("Inside function after execution " + workyday);
return (workyday);
}
我曾想过可能我不应该在函数中使用参数并定义局部变量,但这没有帮助。
1条答案
按热度按时间67up9zun1#
如果你不想一直修改某个日期(就像现在一样),你可以修改你的
getoffday
函数,如下所示:当然,你也可以对
getNextDayOfTheWeek
函数使用同样的方法,这样你就可以得到孤立的结果(不受函数外部变量值的影响)。