JavaScript如何根据给定月份英文全称获取对应上一个月的名称
上一个月查询函数实现方案
核心逻辑
给定的月份数组是按1月到12月的顺序排列的,我们只需要先定位输入月份在数组中的下标,再取下标减1对应的元素即可,1月的特殊情况单独做边界处理即可。
完整代码
// 给定的月份数组 const monthsArray = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; function prevMonth(currentMonth) { // 查找输入月份在数组中的索引位置 const currentIndex = monthsArray.indexOf(currentMonth); // 输入合法性校验,避免传错内容出现异常 if (currentIndex < 0) { return "请输入正确的月份英文全称"; } // 计算上一个月的索引:如果当前是1月(索引为0),上一个月是数组最后一位的12月 const prevIndex = currentIndex === 0 ? monthsArray.length - 1 : currentIndex - 1; return monthsArray[prevIndex]; }
运行示例
- 输入
prevMonth('August')输出结果:July - 输入
prevMonth('January')输出结果:December
简化写法(可选)
如果熟悉模运算,也可以不用三元判断,直接用模12的方式计算下标,代码更简洁:
function prevMonth(currentMonth) { const currentIndex = monthsArray.indexOf(currentMonth); return currentIndex < 0 ? "输入不合法" : monthsArray[(currentIndex - 1 + 12) % 12]; }
加12是为了避免下标为0的时候减1得到负数,模12后就能自动对应到数组最后一位的索引。
内容的提问来源于stack exchange,提问作者Kanika Singla
相关产品推荐
相关产品推荐

