1 javascript performance if-statement
你会如何更有效地编程?
if( randomYear%4==0 ) {
if( randomYear%100==0 ) {
if( randomYear%400==0 ) {
randomDay = 1 + Math.floor(Math.random()*29);
}
else {
randomDay = 1 + Math.floor(Math.random()*28);
}
else{
randomDay = 1 + Math.floor(Math.random()*29);
}
else{
randomDay = 1 + Math.floor(Math.random()*28);
}
Run Code Online (Sandbox Code Playgroud)
首先,我正在使用math.floor因为它包含0并且排除1,这正是我正在寻找的.这样做的目的是确定变量'randomYear'是否是闰年并且在2月有适当的日期.
我主要关注所有if和else语句.顺便说一下,我正在使用Javascript.非常感谢!!
你甚至不需要数学:
var tmp = new Date(year,1,29); // attempt to get February 29th
isleapyear = (tmp.getMonth() == 1);
Run Code Online (Sandbox Code Playgroud)