gpt4 book ai didi

Javascript - 数组覆盖

转载 作者:行者123 更新时间:2023-11-28 19:04:56 25 4
gpt4 key购买 nike

我正在编写一个函数来根据当前日期“计算”工作周的日期。数组项目的 Console.log 在循环中是正确的,但是当我在循环结束时打印数组的内容时,所有项目都具有相同的值。我无法弄清楚我的逻辑出了什么问题。

非常感谢任何兴。

function calculateWorkingDays(){

var weekDates = ["0","1","2","3","4","5","6"];
var currentDate = new Date();
var weekDay = currentDate.getDay();
console.log("Initial weekDay: " + weekDay);

for (var i=0; i<7; i++){
console.log(i);
//check for Sunday (0)
if (weekDay==0){
weekDates[currentDate.getDay()] = currentDate;
//console.log("if i=0: day" + currentDate.getDay());
console.log("date: " + currentDate);
console.log("day: " + currentDate.getDay());
console.log("weekDates" + currentDate.getDay() + " " + weekDates[currentDate.getDay()]);
//set to Monday (1)
weekDay = 1;
currentDate.setDate(currentDate.getDate()-6);

} else {
if (weekDay<6) {
weekDates[currentDate.getDay()] = currentDate;
console.log("date: " + currentDate);
console.log("day: " + currentDate.getDay());
console.log("weekDates" + currentDate.getDay() + " " + weekDates[currentDate.getDay()]);
weekDay = weekDay + 1;
} else {
weekDates[currentDate.getDay()] = currentDate;
console.log("date: " + currentDate);
console.log("day: " + currentDate.getDay());
console.log("weekDates" + currentDate.getDay() + " " + weekDates[currentDate.getDay()]);
// set to Sunday (0)
weekDay = 0 ;
}
currentDate.setDate(currentDate.getDate()+1);
}

}

console.log(weekDates.toString());


}

最佳答案

问题是您使用相同的内容填充 weekDates 数组 - DateTime 对象(存储在 currentDate 变量中)。这条递增线...

currentDate.setDate(currentDate.getDate()+1);

...不会在 currentDate 中分配新对象 - 它会增强现有对象。

解决方案是: clone或序列化该对象(这取决于您之后要使用它做什么)。

<小时/>

作为旁注,您的方法可以简化:不必检查循环内的日期,只需始终从星期一开始循环即可。例如:

var currentDate = new Date();
var weekDay = currentDate.getDay();
if (weekDay === 0) {
weekDay = 7;
}
currentDate.setDate(currentDate.getDate() - (weekDay - 1));

var weekDays = [currentDate];
var currentTimestamp = +currentDate;
var msInDay = 1000 * 24 * 60 * 60;
for (var i = 1; i < 7; i++) {
weekDays.push(new Date(currentTimestamp + i * msInDay));
}
console.log(weekDays);

此代码将对象存储在数组中;如果没有必要,只需序列化(使用 toString() 或任何其他适合您需要的方法)存储的 DateTimes。

关于Javascript - 数组覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31878655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com