Javascript:在数组末尾重新启动一次循环

编程入门 行业动态 更新时间:2024-10-28 12:17:00
本文介绍了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:在数组末尾重新启动一次循环

本文发布于:2023-10-23 01:32:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519340.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:末尾   数组   重新启动   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!