JavaScript 程序:检查闰年

要理解此示例,您应了解以下 JavaScript 编程 主题


如果满足以下条件,则年份是闰年

  1. 该年份是400的倍数。
  2. 该年份是4的倍数,而不是100的倍数。

示例1:使用if...else检查闰年

// program to check leap year
function checkLeapYear(year) {

    //three conditions to find out the leap year
    if ((0 == year % 4) && (0 != year % 100) || (0 == year % 400)) {
        console.log(year + ' is a leap year');
    } else {
        console.log(year + ' is not a leap year');
    }
}

// take input
const year = prompt('Enter a year:');

checkLeapYear(year);

输出

Enter a year: 2000
2000 is a leap year

在上面的程序中,检查三个条件以确定年份是否为闰年。

%运算符返回除法的余数。


示例2:使用newDate()检查闰年

// program to check leap year
function checkLeapYear(year) {

    const leap = new Date(year, 1, 29).getDate() === 29;
    if (leap) {
        console.log(year + ' is a leap year');
    } else {
        console.log(year + ' is not a leap year');
    }
}

// take input
const year = prompt('Enter a year:');

checkLeapYear(year);

输出

Enter a year: 2000
2000 is a leap year

在上面的程序中,检查二月是否包含29天。

如果二月包含29天,则该年为闰年。

new Date(2000, 1, 29)根据指定的参数给出日期和时间。

Tue Feb 29 2000 00:00:00 GMT+0545 (+0545)

getDate()方法返回月份中的日期。


另请阅读

在我们结束之前,让我们用下面的挑战来测试您对JavaScript程序检查闰年的知识!

挑战

编写一个函数来检查年份是否为闰年。

  • 如果年份能被4整除,它可能是闰年。但是,如果该年份也能被100整除,那么它必须也能被400整除。
  • 例如,1996年是闰年,因为它能被4整除,而不能被100整除。
  • 1900年不是闰年,因为尽管它能被4100整除,但不能被400整除。
  • 如果year是闰年,则返回"Leap"。否则,返回"Noleap"
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战