繁体   English   中英

使用Dates对象时,while循环的行为异常

[英]While loop not behaving as expected using Dates objects

我正在制作一个数组,该数组以40分钟的间隔存储开始时间和之后的时间。

基本上检查一下,将开始时间添加到数组,然后递增重复。

  //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));
  }

以下是日志的屏幕截图:

开始和结束时间:

img

数组的日志:

img2

在数组中,我发现奇怪的是,为什么初始开始时间9不是索引0,为什么最后一个索引是结束时间,而while时间循环条件失败了。

在您的循环中:

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

最后一行将新的Date分配给变量之前 修改startTime Date对象。 因此,当.push()发生时,日期是正确的,但它会在循环的最后一行中更改。

相反,请先创建一个新日期,然后再进行更改:

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));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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