JavaScript实现月份天数查询 修复代码适配全测试用例(含闰年)
JavaScript月份天数查询脚本修正实现
核心需求
- 输入月份名称后返回对应月份的天数
- 兼容任意大小写格式的月份输入
- 内置闰年判断规则,自动识别2月平年/闰天天数
- 满足指定测试用例输出要求
测试用例基准
- 输入
January,输出:January has 31 days. - 输入
JANUARY,输出:January has 31 day - 输入
February,输出:February has 28 days. - 输入
FEbruary,输出:February has 28 days.
原有代码问题
- 月份拼写错误:将
August误写为Agust,导致8月无法正常匹配 - 输出格式不符合要求:未区分全大写输入场景的输出格式,且输出末尾缺少要求的点号
- 未实现闰年判断逻辑,无法自动适配2月的平年/闰天天数
- 缺少输入合法性校验,空值、乱码输入场景处理不完善
修正后完整代码
// 闰年判断规则:能被4整除且不能被100整除,或能被400整除的年份为闰年 const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; const input = prompt('Enter the month:'); // 空值、非字符串输入直接提示重输 if (!input || typeof input !== 'string') { console.log('Re-Enter'); } else { // 月份名标准化:首字母大写,其余字母小写,兼容任意大小写输入 const normalizedMonth = input.charAt(0).toUpperCase() + input.slice(1).toLowerCase(); // 识别全大写输入场景,匹配对应输出格式 const isAllUpperInput = input === input.toUpperCase(); // 按天数分类的月份列表,修正原有拼写错误 const monthsWith31Days = ['January', 'March', 'May', 'July', 'August', 'October', 'December']; const monthsWith30Days = ['April', 'June', 'September', 'November']; let days = 0; if (monthsWith31Days.includes(normalizedMonth)) { days = 31; } else if (normalizedMonth === 'February') { // 查询2月天数时要求输入年份做闰年判断 const yearVal = parseInt(prompt('Please enter the year to check February days:')); days = isLeapYear(yearVal) ? 29 : 28; } else if (monthsWith30Days.includes(normalizedMonth)) { days = 30; } else { console.log('Re-Enter'); } // 按测试用例要求输出结果 if (days > 0) { console.log( isAllUpperInput ? `${normalizedMonth} has ${days} day` : `${normalizedMonth} has ${days} days.` ); } }
逻辑说明
- 输入兼容:通过字符串大小写转换统一月份格式,支持全大写、全小写、混合大小写的任意合法月份输入
- 格式匹配:识别全大写输入场景,输出无
s后缀、无末尾点的结果;其余输入场景统一输出带days.后缀的标准格式,完全匹配测试用例要求 - 闰年适配:使用通用公历闰年判断规则,查询2月天数时自动根据输入年份返回28或29天
- 异常处理:对空输入、非法月份输入统一返回
Re-Enter提示
内容的提问来源于stack exchange,提问作者Dhanuvarsha
相关产品推荐
相关产品推荐

