因此,我尝试获取特定范围内的天数数组,以符合ISOWeekday (返回1-7,其中1是星期一,7是星期日)

因此,如果工作周从星期日(7)开始,到星期二(4)结束,

我需要输出此数组:7,1,2,3,4

const startWeek = 7;
const endWeek = 4;
for (let i = 1; i < 7; i++) {
  if (i > startWeek && i < endWeek) {
    console.log(i);
  }
}

最佳答案

您可以使用模运算,如下所示:

const startWeek = 7;
const endWeek = 4;
for (let i = 0; i <= (endWeek + 7 - startWeek) % 7; i++) {
    let week = (startWeek + i - 1) % 7 + 1;
    console.log(week);
}


使用Array.from的回调函数参数以功能方式编写:

const startWeek = 7;
const endWeek = 4;
var weeks = Array.from(Array((endWeek + 7 - startWeek) % 7 + 1),
                       (_,i) => (startWeek + i - 1) % 7 + 1);
console.log(weeks);

07-24 19:13