tell me how to make sure that when the array element reaches Saturday, the array starts repeating again | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

tell me how to make sure that when the array element reaches Saturday, the array starts repeating again

let dayWeek = new Date(); let days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; let d = new Date().getDay() let choose = confirm('Want to see the next day?'); while (choose == true) { alert(days[d]) d++; let choose = confirm('Want to see the next day?'); if (choose == false) { break; } }

18th Apr 2021, 7:42 PM
Тимур Завьялов
Тимур Завьялов - avatar
6 Answers
+ 3
Just add an if statement that checks if d is greater than or equal to the last index + 1 (length) and sets d to 0 if true.
18th Apr 2021, 8:01 PM
ChaoticDawg
ChaoticDawg - avatar
+ 3
//Thank you all, I did it so let dayWeek = new Date(); let days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; let d = new Date().getDay() alert("Today is " + days[d]); let choose = confirm('Want to see the next day?'); while (choose == true) { d++; alert(days[d]) if (d >= 6) { d = -1; } let choose = confirm('Want to see the next day?'); if (choose == false) { break; } } //Everything seems to be working))
18th Apr 2021, 8:32 PM
Тимур Завьялов
Тимур Завьялов - avatar
+ 2
i believe you need a if statement where d++ is. if d is greater than or equal to 6, set d equal to 0. an example of a shorthand (ternary) conditional if statement is provided below: d >= 6 ? d = 0: d++; or if you prefer: if (d >= 6) { d = 0 } else { d++ };
18th Apr 2021, 8:01 PM
you are smart. you are brave.
you are smart. you are brave. - avatar
+ 2
Andrew Choi Your ternary should be like; d = d >= 6 ? 0 : ++d; Using an if statement could be a few different ways depending on where you use d++ or ++d. d++ if (d >= 7) d = 0; if (++d >= 7) d = 0; if (d++ >= 6) d = 0; Etc.
18th Apr 2021, 8:14 PM
ChaoticDawg
ChaoticDawg - avatar
+ 2
ChaoticDawg i appreciate the input. looks like either options will work.
18th Apr 2021, 8:20 PM
you are smart. you are brave.
you are smart. you are brave. - avatar
+ 2
Martin Taylor too true. Lol and a very common solution. Sometimes, I just use the K.I.S.S. method instead for the question, so I don't need to explain my previous explanation.
18th Apr 2021, 11:55 PM
ChaoticDawg
ChaoticDawg - avatar