在JavaScript中判断一个年份是否为闰年,可以通过以下方法实现:
闰年是为了弥补地球绕太阳公转周期(约365.2422天)与公历年的差异而设立的。闰年的规则如下:
以下是一个判断闰年的JavaScript函数示例:
function isLeapYear(year) {
if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
return true;
} else {
return false;
}
}
// 示例用法
console.log(isLeapYear(2000)); // 输出: true
console.log(isLeapYear(1900)); // 输出: false
console.log(isLeapYear(2024)); // 输出: true
year % 4 === 0
:检查年份是否能被4整除。year % 100 !== 0
:检查年份是否不能被100整除。year % 400 === 0
:检查年份是否能被400整除。可以将函数简化为一行代码:
const isLeapYear = year => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
这样可以提高代码的简洁性和可读性。
领取专属 10元无门槛券
手把手带您无忧上云