我用 Javascript 编写的函数有问题。我正在尝试获取开始和结束之间的一系列日期。
功能:
function getDateArray(startDate, endDate) {
var dateArray = new Array(),
currentDate = new Date(startDate),
lastDay = new Date(endDate);
while (currentDate <= lastDay) {
if (!(currentDate.getUTCDay() === 0 || currentDate.getUTCDay() === 6)) {
//currentDate.toUTCString(); //This line is redundant
dateArray.push(currentDate);
}
currentDate.setDate(currentDate.getDate() + 1);
}
return dateArray;
}
每当我使用两个日期调用此函数时,例如:
开始日期 = 10/6/2015 和结束日期 = 10/12/2015
我得到了不需要的结果:
Tue Oct 13 2015 00:00:00 GMT+0200 (South Africa Standard Time)
Tue Oct 13 2015 00:00:00 GMT+0200 (South Africa Standard Time)
Tue Oct 13 2015 00:00:00 GMT+0200 (South Africa Standard Time)
Tue Oct 13 2015 00:00:00 GMT+0200 (South Africa Standard Time)
Tue Oct 13 2015 00:00:00 GMT+0200 (South Africa Standard Time)
Tue Oct 13 2015 00:00:00 GMT+0200 (South Africa Standard Time)
Tue Oct 13 2015 00:00:00 GMT+0200 (South Africa Standard Time)
如果有人可以向我强调这里出了什么问题吗?
最佳答案
这是因为您每次都推送对 currentDate 的引用(由于日期是复杂类型,它们是通过引用传递的)
只需替换此:
dateArray.push(currentDate);
这样:
dateArray.push(new Date(currentDate));
关于javascript - 获取开始日期和结束日期之间的日期数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32969411/