Getting list of dates between two dates not returning correctly JS

前端 未结 3 1001
别那么骄傲
别那么骄傲 2021-01-28 09:23

I have a start date and an end date, and I want to generate a list of dates between (and including) these two dates. But I don\'t get why it isn\'t working...

I pass in

相关标签:
3条回答
  • 2021-01-28 10:01

    Because the same object is modified all elements referencing the same object

    0 讨论(0)
  • 2021-01-28 10:02

    Try to add new Date(i), instead of just i:

    function dateList(dateStart, dateEnd) {
      var dates = [];
      for (i = dateStart; i <= dateEnd; i.setDate(i.getDate() + 1)){
        dates.push(new Date(i));
      }
      return dates;
    }
    
    console.log(dateList(new Date('2017-05-08'), new Date('2017-05-12')));

    0 讨论(0)
  • 2021-01-28 10:14

    Your code i.setDate(i.getDate() + 1) doesn't create a new date - it just updates the same Date object over and over. Then you push that object onto the array, which pushes a reference to that object - not a copy of the object.

    A solution would be to create a new Date() inside the loop and setting the value of it, and then pushing this new date onto your array.

    0 讨论(0)
提交回复
热议问题