使用 else if 处理多重条件
在本步骤中,你将学习使用 else if 语句来处理多个条件。当你面临两个以上可能的输出时,else if 允许你按顺序测试一系列条件。
语法如下:
if (condition1) {
// condition1 的代码
} else if (condition2) {
// condition2 的代码
} else {
// 没有条件满足时的代码
}
让我们扩展问候语脚本,以包含一条晚上的消息。我们将“下午”定义为下午 6 点(18:00)之前,而“晚上”定义为之后的所有时间。
- 在
script.js 文件中,更新你的代码以包含一个 else if 条件。现在的逻辑将是:
- 如果小时数小于 12,则为“早上”。
- 否则,如果小时数小于 18,则为“下午”。
- 否则,为“晚上”。
const greetingElement = document.getElementById("greeting");
const currentHour = new Date().getHours();
if (currentHour < 12) {
greetingElement.textContent = "Good Morning!";
} else if (currentHour < 18) {
greetingElement.textContent = "Good Afternoon!";
} else {
greetingElement.textContent = "Good Evening!";
}
- 保存文件并刷新 Web 8080 标签页。问候语现在将根据当前时间准确地反映是早上、下午还是晚上。