函数Date var参数中的JavaScript是否无故更改?

bqjvbblv  于 2022-11-20  发布在  Java
关注(0)|答案(1)|浏览(112)

我是个菜鸟。如果这个问题很愚蠢的话,我很抱歉。我正在为旅行写一个脚本。我需要得到出发的开始日期和结束日期。返回的日期要得到开始/结束日期的偏移量;在调用函数后,出发日期也改变了。我不能理解我的错误。请帮助。

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);
}

我曾想过可能我不应该在函数中使用参数并定义局部变量,但这没有帮助。

67up9zun

67up9zun1#

如果你不想一直修改某个日期(就像现在一样),你可以修改你的getoffday函数,如下所示:

// Gets a date of diff day from given date
function getoffday(diff=0, workyday = new Date()) {
    // we create a new Date object with the value of the provided "workyday" param
    // now we modify only this copied date - the provided date does not change
    const dateCopy = new Date(workyday.getTime());
    console.log("Inside function before execution " + dateCopy);
    dateCopy.setHours(0,0,0,0);
    dateCopy.setDate(dateCopy.getDate() + diff);
    console.log("Inside function after execution " + dateCopy);
    return (dateCopy);
}

当然,你也可以对getNextDayOfTheWeek函数使用同样的方法,这样你就可以得到孤立的结果(不受函数外部变量值的影响)。

相关问题