如何使用switch和console.log?

How to use switch and 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");
}

如何解决这个问题?

你需要先花时间,然后采取第一种方法,去掉之前做的检查,因为这些检查是多余的。

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;
}

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");