Javascript - 数组覆盖

时间:2015-08-07 13:13:09

标签: javascript arrays

我正在写一个函数来计算'基于当前日期的工作周日期。 数组项目的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());


}

1 个答案:

答案 0 :(得分:3)

问题是您使用相同的内容填充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。