如何在纯Javascript中生成按周分组的天列表/天?就像邮件日历中的“周”显示一样

这应该是最终输出

<ul>
  ...
  <li id="currrentWeek" data-week-nr="51">
    <div class="today" data-day="1" data-dayOfMonth="19">monday</div>
    <div data-day="2" data-dayOfMonth="20">tuesday</div>
    <div data-day="3" data-dayOfMonth="21">wednesday</div>
    <div data-day="4" data-dayOfMonth="22">thursday</div>
    <div data-day="5" data-dayOfMonth="23">friday</div>
    <div data-day="6" data-dayOfMonth="24">saturday</div>
    <div data-day="0" data-dayOfMonth="25">sunday</div>
  </li>
  <li id="nextWeek" data-week-nr="52">
    <div data-day="1" data-dayOfMonth="26">monday</div>
    <div data-day="2" data-dayOfMonth="27">tuesday</div>
    <div data-day="3" data-dayOfMonth="28">wednesday</div>
    <div data-day="4" data-dayOfMonth="29">thursday</div>
    <div data-day="5" data-dayOfMonth="30">friday</div>
    <div data-day="6" data-dayOfMonth="31">saturday</div>
    <div data-day="0" data-dayOfMonth="01">sunday</div>
  </li>
  ...
</ul>


谢谢

最佳答案

噢,太酷了,上周我刚好写了(略)难看的代码:

// let's start with a function that gives us all weeks in a range
function* weeks(from, to = new Date()) {
  for (var f = from.getTime(); f <= to; f += 1000 * 60 * 60 * 24 * 7) {
    let d = new Date(f);
    while (d.getDay() === 0 || d.getDay() === 6) {
      d = new Date(d.getTime() + 1000 * 60 * 60 * 24);
     }
     yield d;
  }
}


查找最早日期的助手:

 function earliestDate(dates) {
      return dates.sort((x, y) => y - x).pop();
 }


现在,让我们检查一下哪几天属于某几周

 function* groupByWeek(dates) {
   for(const week of weeks(earliestDate(dates))) {
     const fromWeek = dates.filter(x => x < week);
     dates = dates.filter(x => !fromWeek.includes(x));
     yield dates;
   }
 }


您可以使用Array.from将其作为数组取回。

07-28 07:04