【发布时间】:2018-10-20 06:13:45
【问题描述】:
我正在尝试确定一年是否是闰年。我不确定我在哪里遗漏了一些东西,因为这段代码旨在确定这一点。
感谢您的帮助。
let Year = (year) => {
this.year = year;
};
Year.prototype.isLeap = () => {
return (
this.year % 400 === 0 ||
(this.year % 4 === 0 && (this.year % 100 === 0))
);
};
let year = new Year(2014);
year.isLeap();
谢谢,我想通了。
最初我会使用你们指向 here! 的那种 If 语句,所以我现在正在重构一个更简洁的代码。
我的代码在这一行有问题
(this.year % 4 === 0 && (this.year % 100 === 0))
正确的语法是
(this.year % 4 === 0 && !(this.year % 100 === 0))
【问题讨论】:
-
使用标准函数而不是箭头函数来捕获调用上下文(在
Year和isLeap中) -
你的逻辑是错误的......它认为闰年只有1900,2000,2100等
-
this.year % 4 === 0 && (this.year % 100 !==0 || this.year %400 == 0) -
这个问题在这里已经有了答案:stackoverflow.com/questions/16353211/…
标签: javascript datetime leap-year