我需要比较时间:
var myDate = new Date().getHours();
if (myDate === 07 || myDate === 08) // condition if user's current time is between 7 and 8 AM
{
// do something
}
else if (myDate == 08 || myDate === 09) // condition if user's current time is between 8 AM and 9 AM
// and so on...
}
什么是比较优雅的方式来比较每个小时间隔(07-08、08-09等)?
myDate
是不合适的。const
ant。如此指定。const currentHour = (new Date()).getHours();
08
和09
会完全失败,因为前导零使它被视为八进制数,不允许8或9。switch
的目的。switch( currentHour) {
case 7:
// do something when it is between 07:00:00 and 07:59:59
break;
case 8:
// do something else when it is between 08:00:00 and 08:59:59
break;
}
附加说明,如果您想做一个小时以上的相同操作,则可以这样做。
case 9: case 10: // do the same thing from 09:00:00 to 10:59:59 break;
if([7,8].includes(myDate)) {
} else if([8,9].includes(myDate)) {
}
这是一种更好的方法,更易于扩展。
if([7,8].includes(myDate)) {
} else if([8,9].includes(myDate)) {
}
这是一种更好的方法,更易于扩展。