javascript - 在 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>
解决方案
您的最终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 - 我正在尝试获取一个动态表单,之后需要使用 PHP 将其数据插入数据库
- linux - Candump - candumpanalyzer:找不到命令
- python - 错误:找不到满足要求时间的版本(来自版本:无)
- apache-spark - YARN 在 launch_container.sh 中如何执行 PYSPARK 环境设置
- firebase - Flutter Firebase google登录发布签名密钥问题
- reactjs - 反应减速器,状态不立即更新
- c# - 在没有用户身份验证的情况下使用公开可用的移动应用程序实现 API 安全性的最佳实践是什么?
- python - 正则表达式删除重复的字符和组合
- r - R语言和本福德定律:程序执行中的警告
- razor - 我可以为一个视图使用多个布局吗?