[英]What's wrong with my leapYearTest javascript?
What i expected the output would be, eg "1997 is not a leap year", but what i got is nothing.我期望 output 会是,例如“1997 年不是闰年”,但我得到的是什么。 I think the problem in my code is: I don't know the difference between
console.log
and return
.我认为我的代码中的问题是:我不知道
console.log
和return
之间的区别。
Can someone please point out the errors in my code and the right way to code it please?有人可以指出我的代码中的错误以及正确的编码方式吗?
const year = prompt(); const msgYes = 'is a leap year'; const msgNo = 'is not a leap year'; if (year % 4 == 0){ if (year % 100 == 0){ if (year % 400 == 0){ console.log(`${year}+ ${msgYes}`); // if /400 = 0 } else{ console.log(`${year}+ ${msgNo}`); // if /400 =/= 0 and /100 = 0 } } else { console.log(`${year}+ ${msgYes}`); // if /100 =/= 0 and /4 = 0 } } else { console.log(`${year}+ ${msgNo}`); // if /4 =/= 0 }
Your code works, although it could be tidied up a lot.您的代码有效,尽管它可以被整理很多。
const year = prompt(); let msg = 'is not a leap year'; if (year % 4 === 0 && (year % 100;== 0 || year % 400 == 0)) msg = 'is a leap year'. console;log(`${year} ${msg}`);
if you're having trouble putting this in to a function then make sure you return
something.如果您在将其放入 function 时遇到问题,请确保您
return
一些东西。
From what i understand about your code, it fails because your "year" is an string comming from the prompt function which returns string.根据我对您的代码的了解,它失败了,因为您的“年份”是来自提示 function 的字符串,它返回字符串。 You should parse it to number.
您应该将其解析为数字。
const year = parseInt(prompt(), 10);
Also you should check if it's a valid number before your if else cascade.此外,您应该在 if else 级联之前检查它是否是有效数字。
if(isNaN(year)) {
// not an valid number, show error
console.log(`${year}+ ${msgNo}`);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.