You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 03:54:03