如何使用switch和console.log?

时间:2019-05-11 18:40:41

标签: javascript switch-statement console.log

我要根据一天中的时间设置问候语,并使用log()方法将其写入控制台。

我已经通过以下两种方式对其进行了尝试

const now = new Date(); //Display's Date

switch (true) {
    case (now <= 12):
        console.log("Good Morning");
        break;
    case (now > 12 && now < 16):
        console.log("Good Afternnon");
        break;
    case (now >= 16 && now < 20):
        console.log("Good Evening");
        break;
    case (now >= 20 && now <= 24):
        console.log("Good Night");
        break;
}


switch (now <= 12) {
    case true:
        console.log("Good Morning");
}
switch (now > 12 && now <= 16) {
    case true:
        console.log("Good Afternnon");
}
switch (now >= 16 && now <= 20) {
    case true:
        console.log("Good Evening");
}
switch (now >= 20 && now <= 24) {
    case true:
        console.log("Good Night");
}

如何解决此问题?

2 个答案:

答案 0 :(得分:1)

您需要先花几个小时,然后再采取第一种方法,并删除以前进行的检查,因为这些检查是多余的。

const now = new Date().getHours();

console.log(now);

switch (true) {
    case now <= 12:
        console.log("Good Morning");
        break;
    case now < 16:
        console.log("Good Afternoon");
        break;
    case now < 20:
        console.log("Good Evening");
        break;
    case now <= 24:
        console.log("Good Night");
        break;
}

答案 1 :(得分:0)

switch语句对您不起作用,请尝试简单的if

const hours = (new Date()).getHours();

if (hours <= 12)
  console.log("Good Morning");
else if (hours > 12 && hours < 16)
  console.log("Good Afternnon");
else if (hours >= 16 && hours < 20)
  console.log("Good Evening");
else
  console.log("Good Night");