简体   繁体   中英

Javascript Get Yesterdays Day of Week

I have a string that contains a day of the week (ex "Monday"). I need to figure out how to take this string and get the previous day of the week.

For example if the string contains "Monday" the new string should output "Sunday".

I feel like there is a simple solution (that isn't 7 IF statements) that I'm missing here.

Try

 let yesterday = { 'Monday': 'Sunday', 'Tuesday': 'Monday', 'Wednesday': 'Tuesday', 'Thursday': 'Wednesday', 'Friday': 'Thursday', 'Saturday': 'Friday', 'Sunday': 'Saturday', } console.log(yesterday['Monday']);

One straightforward approach, assuming correct input , would be using arrays:

days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
previousDay = days[(days.indexOf(currentDay)-1+7)%7];

You can use indexOf and return Sun when you exceed array range:

 let currentDay = "Mon"; let days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; let prevDay = days[days.indexOf(currentDay) - 1 ] || "Sun"; console.log(prevDay);

You don't need a lot of if statements, just a function that uses array.length and array.indexOf() :

 let daysOfWeek = ["Monday", "Tuesday", "Wednesday","Thursday","Friday","Saturday","Sunday"]; let yesterday = (today) => { if(daysOfWeek.indexOf(today) === 0){ return daysOfWeek[daysOfWeek.length - 1]; }else{ return daysOfWeek[daysOfWeek.indexOf(today) - 1]; } } console.log(yesterday("Sunday"));

Your solutions could look as follows

 const daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; const index = daysOfWeek.indexOf('Monday'); console.log(index? daysOfWeek[index - 1]: daysOfWeek[6]);

You just find a position of the current day and take the previous one in the array. The only check you should make for the index === 0 because negative indexes do not return elements from the end of the array in JavaScript

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