如果当前时间是凌晨5点至中午,我需要打印“早上好”,如果是12点至5点,则需要打印“下午好”,如果是5点至午夜,则需要打印“晚安”,如果要在午夜之间,请告诉别人上床睡觉。和凌晨5点。
错误的短语/时间继续打印
这是我当前的代码:
var today = new Date()
var curHr = today.getHours()
if (curHr < 5) {
console.log('good morning')
} else if (curHr < 12) {
console.log('good afternoon')
} else if (curHr < 17) {
console.log('good evening')
} else {
console.log('Go to bed')
}
那些说一直有效的人恰好生活在一个可以工作的时区。
答案 0 :(得分:0)
您只需要更改if条件。最简单的方法是从最小的数字开始,然后从早上开始。
如果时间是凌晨5点之前,您可以从
开始 currentHour < 5
等...
var today = new Date()
var curHr = today.getHours()
if(curHr < 5) {
console.log('Go to bed')
} else if (curHr < 12){
console.log('good morning')
} else if (curHr < 17){
console.log('good afternoon')
} else if (curHr < 24){
console.log('good evening')
}
始终进行测试:
var timeArray = [1, 8, 15, 23];
for (var i = 0; i < timeArray.length; i++) {
var curHr = timeArray[i];
if (curHr < 5) {
console.log('Current Time (' + curHr + '): Go to bed')
} else if (curHr < 12) {
console.log('Current Time (' + curHr + '): good morning')
} else if (curHr < 17) {
console.log('Current Time (' + curHr + '): good afternoon')
} else if (curHr < 24) {
console.log('Current Time (' + curHr + '): good evening')
}
}
答案 1 :(得分:0)
我认为您想根据当前时间打印信息 试试这个
var today = new Date()
var curHr = today.getHours()
if (curHr >= 0 && curHr < 6) {
console.log('What are you doing that early?');
} else if (curHr >= 6 && curHr < 12) {
console.log('Good Morning');
} else if (curHr >= 12 && curHr < 17) {
console.log('Good Afternoon');
} else {
console.log('Good Evening');
}
答案 2 :(得分:0)
您还可以跳过范围检查,仅按降序检查最长小时数。
function greeting() {
var hour = new Date().getHours();
if (hour >= 17) return /* 05:00 PM + */ 'Good Evening';
if (hour >= 12) return /* 12:00 PM + */ 'Good Afternoon';
if (hour >= 6) return /* 06:00 AM + */ 'Good Morning';
else return /* 00:00 AM + */ 'What are you doing that early?';
}
console.log(greeting());
还有一些高尔夫的代码...
var g = {
17 : 'Good Evening', /* 05:00 PM + */
12 : 'Good Afternoon', /* 12:00 PM + */
6 : 'Good Morning', /* 06:00 AM + */
0 : 'What are you doing that early?' /* 00:00 AM + */
}
const f=()=>(h=>g[Object.keys(g).map(x=>parseInt(x,10)).sort((a,b)=>b-a).find(k=>h>=k)])(new Date().getHours());
console.log(f());