javascript 如何设置每小时的任务?

2uluyalo  于 2022-12-28  发布在  Java
关注(0)|答案(2)|浏览(158)

我有一个包含一个工作日所有时间的数组:

let daySchedule = ["08:00", "09:00", "10:00", ... , "20:00"];

let task = 2; // the number of times a task should be performed during the day
let taskDescription = "Cleaning";

在这种情况下,输出应为:

08:00 - Coffee break
**09:00 - Cleaning**
10:00 - Coffee break
**11:00 - Cleaning**
12:00 - Coffee break
**13:00 - Cleaning**]

等等......我试着使用一个For循环,并将“Cleaning”添加到数组中,但我如何设置它,使它只显示每2行?

whlutmcx

whlutmcx1#

下面是一个使用modulo函数来完成所需操作的示例。有关modulo的更多信息:https://en.wikipedia.org/wiki/Modulo_operation.

let daySchedule = ["08:00", "09:00", "10:00", "20:00"];
let task = 2; // the number of times a task should be performed during the day
let taskDescription = "Cleaning";
for(i=0;i<daySchedule.length;i++)
{
  if(i%task === 1)
  {
  console.log(daySchedule[i] + " " + taskDescription);
  }
  else
  {
  console.log(daySchedule[i] + " Coffee Break");
  }
  
}
vsikbqxv

vsikbqxv2#

所以对于你的问题,代码应该是:

let daySchedule = ["08:00", "09:00", "10:00", ... , "20:00"];

let task = 2;
let taskDescription = "Cleaning";
let temp= 0;

while(temp!=daySchedule.length){
     temp%task===1 
     ? (console.log(daySchedule[temp] + " " + taskDescription)) 
     : (console.log(daySchedule[temp] + " Coffee Break"))
     temp++;
 
}

提示:-尝试使用三元运算符而不是if-else以获得更好的代码质量和理解

相关问题