问题描述
- 麻烦大家帮我看看下面的js函数有什么问题?
- 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/102015/06/032015/05/272015/05/202015/05/132015/05/062015/04/292015/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);前面就行了
时间: 2024-08-02 06:43:38