在JavaScript中寻找下一个leap年

我们需要编写一个函数,该函数需要一个正整数n并返回下一个n个leap年的数组。我们将把这个问题分为三个部分-

第1部分:通过JS查找当前年份

通过JS查找当前年份的代码将是-

// getting the current year from a new instance of Date object
const year = new Date().getFullYear();

第2部分:检查leap年

现在,我们将编写一个isLeap()函数,该函数接受一个数字,并根据该数字是否为a年返回一个布尔值。

如果满足这两个条件中的至少一个,则将一年视为a年-

  • 是400的倍数。

  • 它是4的倍数,而不是100的倍数。

记住这些事情,让我们编写函数isLeap()-

// function to check for a leap year
const isLeap = year => {
   return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);
};

第三部分:寻找下一个n年

示例

// function to check for a leap year
const isLeap = year => {
   return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);
};
const nextNLeap = n => {
   const arr = [];
   let year = new Date().getFullYear()+1;
   while(arr.length < n){
      if(isLeap(year++)){
         arr.push(year-1);
      };
   };
   return arr;
};
console.log(nextNLeap(5));
console.log(nextNLeap(25));

输出结果

控制台中的输出将为-

20242028203220362040 ]
[
   20242028203220362040,
   20442048205220562060,
   20642068207220762080,
   20842088209220962104,
   21082112211621202124
]
猜你喜欢