我相信问题源于 && 运算符,因为当我将其切换到 || 时我得到了结果。如果我保留它 && 结果不会返回。
我的代码如下。
<!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>
最佳答案
您的最终成绩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>
关于javascript - 在 IF 语句中使用 and 运算符时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52638074/