function getDateBy8Week(theDate){
var dateSet = [];
theDate = new Date(theDate);
for(var i=0;i<8;i++){
alert(theDate);
dateSet.push(theDate);
theDate = new Date(theDate.setDate(theDate.getDate()-7));
}
alert("haha");
for(var j=0;j<dateSet.length;j++){
alert(dateSet[j]);
}
return dateSet;
}
当theDate传入"2015/06/17"时,最后打印出2015/06/10,2015/06/03,2015/05/27,2015/05/20,2015/05/13,2015/05/06,2015/04/29,2015/04/22,我明明已经将2015/06/17保存在数组中,而数组中没有保存2015/04/22,为什么会出现如下结果?
对象存储的是地址
theDate = new Date(theDate.setDate(theDate.getDate()-7)); 你在还没有给theDate new新地址之前 已经改变了上一个地址存储的值
所以没有06/17,是这个样子咯
//theDate = new Date(theDate.setDate(theDate.getDate()-7));
theDate = new Date(theDate.getDate()-7);
在 new Data() 之前 theDate 和数组成员是同一个对象,theDate.setDate() 等于修改了数组成员的值。
第一个for循环跑8次,2015/06/17~2015/04/29正好8个周,如果想输出2015/04/22
theDate = new Date(theDate.setDate(theDate.getDate()-7));
写在dateSet.push(theDate);前面就行了