Javascript:在数组末尾重新启动一次循环 [英] Javascript: Restart loop once at the end of an array

查看:31
本文介绍了Javascript:在数组末尾重新启动一次循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了这个问题,在任何地方都找不到很好的答案(因此就是问题).

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 amount of times.

在这种特殊情况下,我在一周中有几天的日期,我想使用 Date.getDay()显示从今天的星期几开始的接下来7天的日期名称,其中,返回值从0(星期日)到6(星期六).我可以创建接下来7天名称的数组,但由于当前循环而我一直跳过一个名称.这就是我到目前为止所得到的.

In this particular context I have an array of days in the week and i want to display the names of days for the next 7 days from today's day of the week using Date.getDay() ,which, returns a value from 0 (sunday) to 6 (saturday). I am able to create an array of the next 7 day names except I keep skipping one because of my current loop. Here's what i've got so far.

我的预期输出是:

[星期五",星期六",星期日",星期一",星期二",星期三",星期四"]

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++) {
  if (dayNum + 1 === 7) {
    dayNum = 0;
    for (j = 0; j < todayNum; j++) {
      week.push(dayNames[dayNum])
      dayNum++
    }
    week.push(dayNames[dayNum]);
    dayNum++
  } else {
    week.push(dayNames[dayNum + 1]);
    dayNum++;
  }

}
console.log(week);

我确实看到我的"for"中的"if"是一个人跳过的原因,但是我似乎无法解决该问题.谢谢大家

I do see that my "if" in my "for" is the reason one is skipping but i can't seem to get my head around how to fix. Thanks y'all

推荐答案

您可以使用

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);

这篇关于Javascript:在数组末尾重新启动一次循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆