条件语句用于根据不同的条件执行不同的操作。
通常,当您编写代码时,您希望针对不同的决策执行不同的操作。
您可以在代码中使用条件语句来执行此操作。
在 JavaScript 中,我们有以下条件语句:
使用 if
指定在指定条件为 true 时要执行的代码块
使用 else
指定要执行的代码块,如果条件相同 错误的
如果第一个条件为 false,则使用 else if
指定要测试的新条件
使用 switch
指定要执行的许多替代代码块
switch
语句将在下一章中介绍。
if
语句使用 if
语句指定 JavaScript 代码块 如果条件为真则执行。
if (condition) {
// block of code to be executed if the condition is true
}
请注意,if
是小写字母。大写字母(If 或 IF)将生成 JavaScript 错误。
如果时间小于,请说“美好的一天”问候语 18:00:
if (hour < 18) {
greeting = "Good day";
}
问候语的结果将是:
自己尝试一下→
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if</h2>
<p>Display "Good day!" if the hour is less than 18:00:</p>
<p id="demo">Good Evening!</p>
<script>
if (new Date().getHours() < 18) {
document.getElementById("demo").innerHTML = "Good day!";
}
</script>
</body>
</html>
else
语句使用 else
语句指定要执行的代码块 如果条件为则执行 错误的。
if (condition) {
// block of code to be executed if the condition is true
}
else {
// block of code to be executed if the condition is false
}
如果时间少于 18 点,则创建“Good day” 问候语,否则“晚上好”:
if (hour < 18) {
greeting = "Good day";
}
else {
greeting = "Good evening";
}
问候语的结果将是:
自己尝试一下→
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if .. else</h2>
<p>A time-based greeting:</p>
<p id="demo"></p>
<script>
const hour = new Date().getHours();
let greeting;
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
</script>
</body>
</html>
else if
语句如果第一个条件为 false,请使用 else if
语句指定新条件。
if (condition1) {
// block of code to be executed if condition1 is true
}
else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
如果时间小于 10:00,则创建“Good 早晨” 问候语,如果没有,但时间小于 20:00,则创建“Good day”问候语, 否则是“晚上好”:
if (time < 10) {
greeting = "Good morning";
}
else if (time < 20) {
greeting = "Good day";
}
else {
greeting = "Good evening";
}
问候语的结果将是:
自己尝试一下→
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if .. else</h2>
<p>A time-based greeting:</p>
<p id="demo"></p>
<script>
const time = new Date().getHours();
let greeting;
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
</script>
</body>
</html>
随机链接
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.random()</h2>
<p id="demo"></p>
<script>
let text;
if (Math.random() < 0.5) {
text = "<a href='https://w3schools.com'>Visit W3Schools</a>";
} else {
text = "<a href='https://wwf.org'>Visit WWF</a>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>