代码假设用给定的开始日期和结束日期之间的日期填充数组。我正在使用Node.js.
var startDate = moment(startDay);
var endDate = moment(endDay);
var datesBetween = [];
var startingMoment = startDate;
while(startingMoment <= endDate) {
datesBetween.push(startingMoment);
startingMoment.add(1, 'days');
}
console.log(datesBetween);
答案 0 :(得分:4)
每次迭代都需要创建一个新对象,否则每次都会将相同的对象引用推送到数组中。它们都将以最后日期结束,因为它是完全相同的对象
每次都可以使用moment.clone()
克隆对象
var startDay = new Date(2018,1,1);
var endDay = new Date(2018,1,4);
var startDate = moment(startDay);
var endDate = moment(endDay);
var datesBetween = [];
var startingMoment = startDate;
while(startingMoment <= endDate) {
datesBetween.push(startingMoment.clone());// clone to add new object
startingMoment.add(1, 'days');
}
console.log(datesBetween);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js"></script>