查找日期范围内的工作日

时间:2018-06-10 08:51:20

标签: javascript arrays

我试图在一个数组范围内推送日期,但它只推送最后一个日期n次而不是所需的个别日期。

function getBusinessDatesCount(startDatetest, endDatetest) {
    var curDate = startDatetest;
    var weekdays = [];
    while (curDate <= endDatetest) {
        var dayOfWeek = curDate.getDay();
        if (!((dayOfWeek === 6) || (dayOfWeek === 0))) {
            weekdays.push(curDate);
        }
        curDate.setDate(curDate.getDate() + 1);
    }
    console.log(weekdays);
}
var startDatetest = new Date('05/03/2016');
var endDatetest = new Date('05/10/2016');
var numOfDates = getBusinessDatesCount(startDatetest, endDatetest);

enter image description here

2 个答案:

答案 0 :(得分:1)

目前内存中只有两个date个对象,startDatetestendDatetest - 更改curDate将更改startDatetest,因为对象变量实际上是参考Javascript中的内存位置。 (创建引用该对象的新变量,例如curDate = startDatetest,不会克隆该对象,它只会复制对象在内存中的位置的引用)。您需要克隆 date对象:

function getBusinessDatesCount(startDatetest, endDatetest) {
  var curDate = startDatetest;
  var weekdays = [];
  while (curDate <= endDatetest) {
    var dayOfWeek = curDate.getDay();
    if (!((dayOfWeek === 6) || (dayOfWeek === 0))) {
      weekdays.push(new Date(curDate.getTime()));
    }
    curDate.setDate(curDate.getDate() + 1);
  }
  console.log(weekdays);
}
var startDatetest = new Date('05/03/2016');
var endDatetest = new Date('05/10/2016');
var numOfDates = getBusinessDatesCount(startDatetest, endDatetest);

答案 1 :(得分:1)

您需要将新日期对象推送到数组中。否则,您将一遍又一遍地添加对同一对象的引用。

function getBusinessDatesCount(startDatetest, endDatetest) {
    var curDate = startDatetest;
    var weekdays = [];
    while (curDate <= endDatetest) {
        var dayOfWeek = curDate.getDay();
        if(!((dayOfWeek === 6) || (dayOfWeek === 0))) {
           weekdays.push(new Date(curDate));
        }   
        curDate.setDate(curDate.getDate() + 1);
    }
    console.log(weekdays);
}
var startDatetest = new Date('05/03/2016');
var endDatetest = new Date('05/10/2016');
var numOfDates = getBusinessDatesCount(startDatetest,endDatetest);