首页 > 解决方案 > 我希望我的 JavaScript 代码返回“这是闰年”,但它返回“不是闰年”

问题描述

我希望我的 JavaScript 代码返回“这是闰年”,但它返回“不是闰年”。

function isLeap(year) {
  if (year % 4 === 0) {
    if (year % 100 === 0) {
      if (year % 400 === 0) {
        return 'it is a leap year';
      } else {
        return 'not a leap year';
      }
    } else {
      return 'It is a leap year';
    }
  } else {
    return 'not a leap year';
  }
}

console.log('2000: ', isLeap(2000));
console.log('2001: ', isLeap(2001));
console.log('2002: ', isLeap(2002));
console.log('2003: ', isLeap(2003));
console.log('2004: ', isLeap(2004));

标签: javascript

解决方案


如果你只是调用isLeap();,那么参数yearundefined. 你必须通过你想在你的函数中测试的年份,例如:isLeap(2020);


推荐阅读