首页 > 解决方案 > 在 IF 语句中使用 and 运算符时遇到问题

问题描述

我相信问题源于 && 运算符,因为当我将其切换到 || 时会得到结果。如果我保留它 && 结果不会返回。

我的代码如下。

<!DOCTYPE html>
<html>
<body>

<p id="greeting"></p></center>

<script>
var time = new Date().getHours();
let phrase = "";

if ((time > 6) && (time < 12)) {
    phrase = "Good Morning";
} else if ((time > 12) && (time < 18)) {
    phrase = "Good Afternoon";
} else if ((time >= 18) && (time <= 6)) {
    phrase = "Good Evening";
}
document.getElementById("greeting").innerHTML = phrase;
</script>

</body>
</html>

标签: javascript

解决方案


您的最终if陈述永远不会评估为true; time不能同时大于(或等于)18小于(或等于)6。您正在这里寻找一个OR声明 ( ||),因为time总是在下午 6 点之后 ( > 18) 或早上 6 点之前 ( < 6) - 它不能同时是:

else if ((time >= 18) || (time <= 6))

话虽如此,这次更正现在将涵盖所有可能的时间,这意味着最终条件实际上是无关紧要的;如果前两个if语句中的任何一个没有被介入,上述条件总是会得到满足。因此,您可以简单地将其替换为else

var time = new Date().getHours();
let phrase = "";

if ((time > 6) && (time < 12)) {
  phrase = "Good Morning";
} else if ((time > 12) && (time < 18)) {
  phrase = "Good Afternoon";
} else {
  phrase = "Good Evening";
}

document.getElementById("greeting").innerHTML = phrase;
<!DOCTYPE html>
<html>

<body>
  <center>
    <h2>Individual Tech Proficiency 1</h2>
    <h4>Emulator</h4>
    <p id="greeting"></p>
  </center>
</body>

</html>


推荐阅读