简体   繁体   中英

While loop not behaving as expected using Dates objects

Im making an array that stores a start time and times following that in 40 min intervals.

Basically check, add the start time to the array then increment repeat.

  //Array Of All Available times.
  var timeArray = [];
  //Start time this begins with 9:00
  var startTime = new Date(`date setup here`);
  //End Time this is 17:00
  var endTime = new Date(`date setup here`);
  while (startTime < endTime) {
    //Push Start Time to Array
    timeArray.push(startTime);
    //Add 40 minutes to startTime
    startTime = new Date(startTime.setMinutes(startTime.getMinutes() +40));
  }

Here are screenshots of the logs:

Start and end Times:

img

Log of Array:

img2

In the array I find it strange why the inital start time of 9 is not index 0 and why the last index is the end time which should of failed the while loop condition.

In your loop:

while (startTime < endTime) {
    //Push Start Time to Array
    timeArray.push(startTime);
    //Add 40 minutes to startTime
    startTime = new Date(startTime.setMinutes(startTime.getMinutes() +40));
}

the last line modifies the startTime Date object before it assigns the new Date to the variable. Thus, when the .push() happens the date is correct, but it changes in that last line of the loop.

Instead, make a new date first and then change it:

while (startTime < endTime) {
    //Push Start Time to Array
    timeArray.push(startTime);
    //Add 40 minutes to startTime
    startTime = new Date(startTime);
    startTime.setMinutes(startTime.getMinutes() +40));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM