在JavaScript中查找接下来的n个闰年


我们需要编写一个函数,该函数接收一个正整数n并返回接下来n个闰年的数组。我们将把这个问题分成三个部分:

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

通过JS查找当前年份的代码如下:

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

第二部分:检查闰年

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

如果满足以下两个条件中的至少一个,则该年份被认为是闰年:

  • 它是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));

输出

控制台中的输出将是:

[ 2024, 2028, 2032, 2036, 2040 ]
[
   2024, 2028, 2032, 2036, 2040,
   2044, 2048, 2052, 2056, 2060,
   2064, 2068, 2072, 2076, 2080,
   2084, 2088, 2092, 2096, 2104,
   2108, 2112, 2116, 2120, 2124
]

更新于:2020年8月28日

502 次浏览

启动你的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.