闰年脚本,每次都返回false

时间:2017-12-10 20:43:10

标签: javascript

我正在编写代码来检查年份是否跳跃,但每次都会返回false。

<script src="dateLibrary.js"> </script>
<script>
function myLeapYearFunction(aDate)
{
var year = parseFloat(window.prompt("Enter a year: "));
var aDate = new Date(year);
document.write("is it leap? " + isLeapYear(aDate));
}
myLeapYearFunction();
</script>

dateLibrary.js

function isLeapYear(aDate)
/*********************************************************************/
/* Argument is a Date object. Function returns the boolean value     */
/* true if the year is a leap year. False otherwise,                 */
/*********************************************************************/

{
var year = aDate.getFullYear();
if (((year % 4) == 0) && ((year % 100)!=0) || ((year % 400) == 0))
    return (true)
else
    return (false)
}; 
/*************************End of function*****************************/

我现在已经尝试了4个小时,但却找不到错误。

我真的很感谢你的帮助。

3 个答案:

答案 0 :(得分:1)

不要使用Date对象,因为您只测试年份而不是日期。

其他无关的更改包括使用parseInt代替parseFloat,并重构您的isLeapYear功能。

function myLeapYearFunction() {
   var year = parseInt(window.prompt("Enter a year: "));
   console.log("is it leap? " + isLeapYear(year));
}

myLeapYearFunction();

function isLeapYear(year) {
   var fourth = year % 4 == 0;
   var hundredth = year % 100 == 0;
   var fourHundredth = year % 400 == 0;
   return fourth && (!hundredth || fourHundredth);
}; 

答案 1 :(得分:0)

尝试使用:

var aDate = new Date();
var year = aDate.getFullYear();
document.write("is it leap? " + isLeapYear(year));

代替。

  • 由于Date()类不接受任何“年”参数
  • 有4种方法可以启动日期:

    1. 新日期()

    2. 新日期(毫秒)

    3. 新日期(dateString)

    4. 新日期(年,月,日,小时,分钟,秒,毫秒)

答案 2 :(得分:0)

尽可能少做一些改动:

<script src="dateLibrary.js"> </script>
<script>
function myLeapYearFunction(aDate)
{
var year = parseFloat(window.prompt("Enter a year: "));
// initialize without year and set year afterwards.
var aDate = new Date();
aDate.setYear(year);
document.write("is it leap? " + isLeapYear(aDate));
}
myLeapYearFunction();
</script>