js实现闰年


判断闰年的规则
闰年的判断遵循以下规则:
- 年份能被4整除但不能被100整除的是闰年
- 年份能被400整除的也是闰年
使用条件语句实现
function isLeapYear(year) {
if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
return true;
}
return false;
}
简化实现方式
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
使用Date对象验证
function isLeapYear(year) {
return new Date(year, 1, 29).getMonth() === 1;
}
测试示例
console.log(isLeapYear(2000)); // true
console.log(isLeapYear(1900)); // false
console.log(isLeapYear(2024)); // true
console.log(isLeapYear(2023)); // false
注意事项
- 输入年份应为正整数
- 公元前的年份需要考虑历法差异
- 实际应用中可能需要添加参数验证






