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

实现根据输入月份数字获取天数功能,无效输入输出Error

完善Node.js代码实现月份天数查询功能

需求

根据输入的月份数字,获取该月份对应的天数;若输入的数字不在有效范围(1-12)内,则输出Error。
示例输入:8
示例输出:31

修正后的完整代码

// Getting input via STDIN
const readline = require("readline");

const inp = readline.createInterface({
  input: process.stdin
});

const userInput = [];

inp.on("line", (data) => {
  userInput.push(data);
});

inp.on("close", () => {
  // 提取输入的月份并转为数字类型
  const month = parseInt(userInput[0]);

  // 校验月份是否在有效范围
  if (isNaN(month) || month < 1 || month > 12) {
    console.log("Error");
    return;
  }

  // 定义获取月份天数的函数
  const getDaysInMonth = function(month) {
    // 利用Date对象特性:传入"年份, 目标月份, 0"会返回目标月份的最后一天
    // 这里选2024是闰年,确保2月天数计算准确
    return new Date(2024, month, 0).getDate();
  };

  // 调用函数并打印结果
  console.log(getDaysInMonth(month));
});

关键修改说明

  • 输入处理与校验:将输入字符串转为数字,同时检查是否为有效数字、是否在1-12范围内,不符合直接输出Error
  • 函数参数修正:把原函数的year参数改为month,匹配功能需求
  • Date逻辑修正:借助Date对象的特性——当日期参数传0时,会自动定位到上个月的最后一天,这里用闰年2024确保2月天数计算正确
  • 函数调用修正:传入正确的月份参数,打印函数返回值而非函数本身

内容的提问来源于stack exchange,提问作者arasu ramanan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 23:45:39