用日期填充数组

时间:2016-09-15 16:31:57

标签: javascript arrays byref

真的不明白为什么我推入数组的日期不是我在控制台中调用数组时出现的日期。即我希望数组中的第一个条目是今天的日期,这是两个警报调用的回复,但是当我检查阵列的第一个位置时,它会改变昨天的日期!?

function sevenDayPeriod(date) {

    for (var i = 0; i <=6; i++) {

        alert(date);    //check to see date is today's date
        dateRange[i] = date;
        alert(dateRange[i]);    //confirm that what I've pushed to array is today's date

        date = date.setDate(date.getDate() - 1);
        date = new Date(date);
    }
};

var dateRange = [];
var today  = new Date();

sevenDayPeriod(today);

由于

2 个答案:

答案 0 :(得分:6)

...
dateRange[i] = date;
alert(dateRange[i]);    //confirm that what I've pushed to array is today's date
date = date.setDate(date.getDate() - 1);
...

在上面第一行中,您将第i个数组元素设置为date(引用),然后显示它,然后使用setDate更改同一个对象,这会导致您的问题,因为数组元素仍指向该修改过的对象 你可以解决这个问题。与另一个类似的

...
var prevDay = new Date();
prevDay.setDate(date.getDate() - 1);
date = prevDay;
...  

或在将其推入数组之前创建它的副本

答案 1 :(得分:2)

function sevenDayPeriod(date) {
    for (var i = 0; i <=6; i++) {
	//date object is as a "pointer", you have to clone it
	var copiedDate = new Date(date);
		
        //alert(date); //check to see date is today's date
        dateRange[i] = copiedDate;
        //alert(dateRange[i]); //confirm that what I've pushed to array is today's date
		
        date = date.setDate(date.getDate() - 1);
        date = new Date(date);
    }
};

var dateRange = [];
var today  = new Date();

sevenDayPeriod(today);

console.log(dateRange);

修改日期时,您也在改变推送日期。你必须克隆它。