简体   繁体   中英

How do I set a task per hour?

I have the following array with all the hours of a working day:

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

The output, in this case, should be:

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

Etc... I tried to use a For loop and add "Cleaning" to the array, but how do I set it, so that it only displays every 2 rows?

Here is an example of using the modulo function to do what you want. For more info on 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"); } }

So for your question, the code would be:-

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++;
 
}

Tip:- Try to use ternary operator instead of if-else for better code quality and understanding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM