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

javascriptweb developmentobject oriented programming更新于 2025/10/22 7:08:17

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

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

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

// 从 Date 对象的新实例获取当前年份
const year = new Date().getFullYear();

第 2 部分:检查闰年

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

如果至少满足这两个条件之一,则该年份被视为闰年 −

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

记住这些,让我们编写函数 isLeap() −

// 检查闰年的函数
const isLeap = year => {
   return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);
};

第 3 部分:查找接下来的 n 个闰年

示例

// 检查闰年的函数
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
]

相关文章


有用资源