JavaScript计算月份天数(含闰年)程序问题求助
你的代码存在这些问题及修复方案
多余的八进制数字判断:你写了
month === 01、month === 03这类条件,但parseInt解析用户输入后得到的是十进制数字,比如输入01会被转成1;而且以0开头的数字在JS里属于八进制(ES5及以前规范),08这类无效八进制数会被强制转成十进制8,这些判断完全多余,直接判断十进制数字即可。闰年判断的逻辑优先级错误:原代码中
(month === 2 || month === 02) && (year % 400 === 0) || (year % 4 === 0 && year % 100 !== 0)的逻辑有问题——因为&&优先级高于||,会导致非2月的月份,只要年份是闰年,也会触发29天的提示。需要把闰年的判断条件整体括起来,确保只有2月时才判断闰年。函数未调用:你定义了
calculateDays函数,但没有执行它,导致代码运行后没有任何计算动作。错误处理后未提前终止函数(可选优化):当输入非法值时,alert后函数虽然不会执行后续else if,但加上
return可以让逻辑更清晰,避免后续不必要的判断。
修正后的代码
// 计算指定月份的天数(考虑闰年) let month = parseInt(prompt('Enter Month', 'Eg. 1')) let year = parseInt(prompt('Enter year', '2023')) function calculateDays(month, year) { if (isNaN(month) || isNaN(year)) { alert('Please Enter in Digit Only') return // 提前终止函数 } else if (month <= 0 || month > 12) { alert(`Please Enter Month Between 1 to 12`) return } else if (month === 1 || month === 3 || month === 5 || month === 7 || month === 8 || month === 10 || month === 12) { alert(`Number of days in month ${month} are 31`) } else if (month === 2 && ((year % 400 === 0) || (year % 4 === 0 && year % 100 !== 0))) { alert(`Number of days in month ${month} are 29`) } else if (month === 2) { alert(`Number of days in month ${month} are 28`) } else { alert(`Number of days in month ${month} are 30`) } } // 调用函数执行计算 calculateDays(month, year)
内容的提问来源于stack exchange,提问作者Technical jangra
相关产品推荐
相关产品推荐

