js实现闰年


判断闰年的规则
闰年判断遵循以下规则:
- 能被4整除但不能被100整除的年份是闰年
- 能被400整除的年份也是闰年
基础实现方法
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
带输入验证的实现
function isLeapYear(year) {
if (typeof year !== 'number' || !Number.isInteger(year)) {
throw new Error('输入必须是整数');
}
if (year < 0) {
throw new Error('年份不能为负数');
}
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
测试示例
console.log(isLeapYear(2000)); // true
console.log(isLeapYear(1900)); // false
console.log(isLeapYear(2020)); // true
console.log(isLeapYear(2021)); // false
批量判断方法
function checkLeapYears(years) {
return years.map(year => ({
year,
isLeap: isLeapYear(year)
}));
}
// 使用示例
const years = [2000, 1900, 2020, 2021];
console.log(checkLeapYears(years));
注意事项
- 输入应为整数年份
- 公元前的年份需要特殊处理(本实现未考虑)
- 格里高利历从1582年开始采用,之前的年份可能有不同规则






