Javascript MomentJS-选择工作日

Javascript MomentJS-选择工作日,javascript,momentjs,Javascript,Momentjs,我有一个日历,你可以在其中选择日期。现在,如果我想选择从一个日期到另一个日期的星期一,我必须单击每个星期一。这就是我写的能够选择特定工作日的多个日期: // selectedDates variable consists already selected dates in form of MomentJS objects let result = [...selectedDates]; // Supplying a dateFrom and dateTo con

我有一个日历,你可以在其中选择日期。现在,如果我想选择从一个日期到另一个日期的星期一,我必须单击每个星期一。这就是我写的能够选择特定工作日的多个日期:

    // selectedDates variable consists already selected dates in form of MomentJS objects
    let result = [...selectedDates];

    // Supplying a dateFrom and dateTo
    const dateFrom = moment().add(-1, "year");
    const dateTo = moment();
    console.log(`Range from ${dateFrom.format("DD-MM-YYYY")} to ${dateTo.format("DD-MM-YYYY")}`)

    const dates = [];
    const indexes = []; // Indexes of common dates

    // Enumerating to get dates that weekday is equal to supplied weekday (not included here)
    // Also checking if those dates are already in the selectedDates array and if true then saving their indexes to an array
    while(dateFrom.add(1, "days").diff(dateTo) < 0) {
        if (dateFrom.format("dd") === weekday) {
            dates.push(dateFrom.clone());
            const index = selectedDates.findIndex(date => date.isSame(dateFrom, "day"));
            if (index > -1) { indexes.push(index); }
        }
    }

    // If there are already less dates in the selectedDates array then I want to select what's left
    // Else just deselect all dates
    if (dates.length > indexes.length) {
        const difference = _.differenceWith(dates, selectedDates, (a, b) => a.isSame(b, "day"));
        result.push(...difference);
    } else {
        result = _.differenceWith(selectedDates, dates, (a, b) => a.isSame(b, "day"));
    }

    return result;
//selectedDates变量以MomentJS对象的形式包含已选择的日期
让结果=[…选定日期];
//提供dateFrom和dateTo
const dateFrom=moment().add(-1,“年”);
const dateTo=力矩();
console.log(`范围从${dateFrom.format(“DD-MM-YYYY”)}到${dateTo.format(“DD-MM-YYYY”)}`)
常数日期=[];
常量索引=[];//常用日期索引
//枚举以获取工作日等于提供的工作日(此处不包括)的日期
//还要检查这些日期是否已在selectedDates数组中,如果为true,则将其索引保存到数组中
while(dateFrom.add(1,“天”).diff(dateTo)<0){
if(dateFrom.format(“dd”)==工作日){
dates.push(dateFrom.clone());
const index=selectedDates.findIndex(date=>date.isName(dateFrom,day));
if(index>-1){index.push(index);}
}
}
//如果selectedDates数组中的日期已经减少,那么我想选择剩下的日期
//否则只需取消选择所有日期
如果(dates.length>index.length){
常数差=uu.差与(日期,选定日期,(a,b)=>a.isSame(b,“日”);
结果:推送(…差异);
}否则{
结果=(所选日期、日期,(a、b)=>a.isSame(b,“日期”);
}
返回结果;
代码按预期工作,但是如果我有一个1年的范围,那么如果选择每个工作日(364个日期),延迟大约为0.5秒


我的问题是,这段代码的性能是否还有改进的余地?我肯定有,但我真的找不到

我想这可能会对你有所帮助:或者这是一个现成的代码,我想也比你的更快:@peter我已经有了所有选定的两个日期之间的工作日。这是第一个
while
循环,速度很快。我想知道,对于while循环之后出现的代码,是否还有其他解决方案—搜索已选择的日期等。