JavaScript:如何将星期数组中的每个元素转换为前一天?现有代码结果不符合预期
I've written the following JavaScript code to shift each weekday in my array to the previous day, but it's not working as expected:
const weekDays = [ { label: 'Mon', name: 'Monday' }, { label: 'Tue', name: 'Tuesday' }, { label: 'Wed', name: 'Wednesday' }, { label: 'Thu', name: 'Thursday' }, { label: 'Fri', name: 'Friday' }, { label: 'Sat', name: 'Saturday' }, { label: 'Sun', name: 'Sunday' }, ]; let daysOfWeek = ['Tue','Thu', 'Sun'] const firstDayIndex = weekDays.findIndex(day => day.label === daysOfWeek[0]) // 获取当前日期索引 daysOfWeek.unshift(weekDays[(firstDayIndex || weekDays.length) - 1].label) // 通过索引添加前一天 daysOfWeek.pop() // 删除最后一个元素 console.log(daysOfWeek)
Right now, the output is ["Mon", "Tue", "Thu"], but I want ["Mon", "Wed", "Sat"] — meaning every element in daysOfWeek should be replaced with the weekday that comes right before it (e.g., Tue → Mon, Thu → Wed, Sun → Sat). How can I fix this code to achieve the desired result?
Solution
The issue with your current code is that you're only adjusting the first element in the array and removing the last one, instead of processing every element to shift it to the previous day. Here's how you can fix this:
- Create a helper object to map each weekday label to its index in the
weekDaysarray — this makes index lookups far faster than repeatingfindIndexcalls in a loop. - Iterate over each element in
daysOfWeek, calculate the index of its previous day, and retrieve the corresponding label. - Handle the edge case where the previous day of "Mon" is "Sun" (since we need to loop around the week).
Here's the revised code:
const weekDays = [ { label: 'Mon', name: 'Monday' }, { label: 'Tue', name: 'Tuesday' }, { label: 'Wed', name: 'Wednesday' }, { label: 'Thu', name: 'Thursday' }, { label: 'Fri', name: 'Friday' }, { label: 'Sat', name: 'Saturday' }, { label: 'Sun', name: 'Sunday' }, ]; // Create a lookup map for quick index retrieval const dayIndexMap = weekDays.reduce((map, day, index) => { map[day.label] = index; return map; }, {}); let daysOfWeek = ['Tue','Thu', 'Sun']; // Process each day to get its previous day daysOfWeek = daysOfWeek.map(dayLabel => { const currentIndex = dayIndexMap[dayLabel]; // Calculate previous index: if current is 0 (Mon), wrap to 6 (Sun), else subtract 1 const previousIndex = currentIndex === 0 ? weekDays.length - 1 : currentIndex - 1; return weekDays[previousIndex].label; }); console.log(daysOfWeek); // Output: ["Mon", "Wed", "Sat"]
Explanation:
- Lookup Map: The
dayIndexMapobject stores each weekday label as a key and its index inweekDaysas the value. This avoids redundantfindIndexcalls, making the code more efficient (especially if your array grows larger). - Mapping Each Day: Using
Array.map()lets us transform every element indaysOfWeekindividually. For each day, we find its current index, compute the previous index (handling the wrap-around for Monday), and grab the corresponding label fromweekDays. - Edge Case Handling: When the current day is Monday (index 0), we set the previous index to
weekDays.length - 1(which is 6, the index for Sunday) instead of-1, which would be invalid.
This approach ensures every element in your array gets shifted to the previous weekday, exactly as you need.
内容的提问来源于stack exchange,提问作者qweeee

