[removed] Restart loop once at the end of an array

前端 未结 5 974
孤独总比滥情好
孤独总比滥情好 2021-01-23 21:31

I recently came across this problem and can\'t find a good answer anywhere (hence the question).

I want to restart the loop once i reach the end yet only loop a finite a

5条回答
  •  囚心锁ツ
    2021-01-23 22:13

    Try using the % operator and just one loop:

    const dayNames = [
      "Sunday",
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday"
    ];
    
    const rawDate = new Date();
    let dayNum = rawDate.getDay();
    const week = [];
    
    for (let i = 0; i < 7; i++) {
        week.push(dayNames[dayNum++ % 7]);
    }
    
    console.log(week);

    Also, the zeroeth day of the week, according to Date.prototype.getDate is Sunday.

提交回复
热议问题