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

前端 未结 5 975
孤独总比滥情好
孤独总比滥情好 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.

    0 讨论(0)
  • 2021-01-23 22:14

    If you want [tomorrow, tomorrow + 1, ..., tomorrow + 6]:

    for (let i = 1; i <= 7; i++) {
      week.push(dayNames[(dayNum + i) % 7]);
    }
    
    0 讨论(0)
  • 2021-01-23 22:25

    You don't need to restart the loop, just use the modulus operator to wrap your array indexes around.

    And you need to fix the order of dayNames so it corresponds with what getDay() returns. And the loop needs to run 7 times, not just 6 to get the entire week.

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

    0 讨论(0)
  • 2021-01-23 22:29

    You could use the remainder operator % for the right index.

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

    0 讨论(0)
  • 2021-01-23 22:35

    You need i < 7 to get the entire next 7 days, then using the modulus operator % which returns the remainder of division and a single for loop will give you the desired result.

     const dayNames = [
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday",
      "Sunday"
    ];
    const rawDate = new Date();
    let dayNum = rawDate.getDay();
    const week = [];
    for (let i = 0; i < 7; i++) {
        week.push(dayNames[(dayNum + i) % dayNames.length]);
    }
    console.log(week);
    
    0 讨论(0)
提交回复
热议问题