JavaScript 条件语句
JavaScript 条件语句:if、else if、else
Section titled “JavaScript 条件语句:if、else if、else”条件语句用于根据指定的条件评估结果是 true(真)还是 false(假)来执行不同的操作。
在编写代码时,经常需要根据某些决策来执行不同的代码块。
JavaScript 提供了以下条件语句:
- 使用
if来指定如果条件为 true 时执行的代码块。 - 使用
else来指定如果条件(来自前面的if)为 false 时执行的代码块。 - 使用
else if来指定一个新的条件,当前面的条件(来自前面的if或else if)为 false 时测试这个新条件。 - 使用
switch来指定基于表达式的值执行许多备选代码块(将在单独的章节中介绍)。
使用 if 语句来执行一个 JavaScript 代码块,仅当指定的条件为 true 时。
if (condition) { // 如果条件为 true,将执行此代码块 }
注意:if 必须是小写字母。使用 If 或 IF 将导致 JavaScript 错误。条件通常是一个计算结果为布尔值(true 或 false)的表达式。 |
|---|
const hour = new Date().getHours(); // 获取当前小时 (0-23)let greeting;
if (hour < 18) { greeting = "Good day";}// 例如,如果 hour 是 10,greeting 将是 "Good day"。// 如果 hour 是 20,greeting 将保持 undefined(或其之前的值)。else 语句
Section titled “else 语句”使用 else 语句来指定如果 if 语句中的条件为 false 时执行的代码块。
if (condition) { // 如果条件为 true,将执行此代码块 } else { // 如果条件为 false,将执行此代码块 }
const hour = new Date().getHours();let greeting;
if (hour < 18) { greeting = "Good day";} else { greeting = "Good evening";}// 如果 hour 是 10,greeting 是 "Good day"。如果 hour 是 20,greeting 是 "Good evening"。else if 语句
Section titled “else if 语句”使用 else if 语句来指定一个新的条件,当前面的条件(来自 if 或另一个 else if)为 false 时测试这个新条件。
if (condition1) { // 如果 condition1 为 true,将执行此代码块 } else if (condition2) { // 如果 condition1 为 false 且 condition2 为 true,将执行此代码块 } else { // 如果 condition1 和 condition2 都为 false,将执行此代码块 }
const time = new Date().getHours();let greeting;
if (time < 10) { greeting = "Good morning";} else if (time < 18) { greeting = "Good day";} else if (time < 22) { greeting = "Good evening";} else { greeting = "Good night";}// 这根据时间提供了更细致的问候语。三元运算符(条件运算符)
Section titled “三元运算符(条件运算符)”JavaScript 还提供了一个条件(三元)运算符,它是简单 if...else 语句的简写形式。它需要三个操作数:一个条件,后面跟着一个问号 (?);然后是一个在条件为 true 时执行的表达式,后面跟着一个冒号 (:);最后是一个在条件为 false 时执行的表达式。
variable = (condition) ? valueIfTrue : valueIfFalse;
const age = 20;const canVote = (age >= 18) ? "Can vote" : "Cannot vote";// canVote 将是 "Can vote"
const isAuthenticated = true;const userName = isAuthenticated ? "Alice" : "Guest";// userName 将是 "Alice"三元运算符虽然简洁,但如果嵌套或过于复杂,可能会变得难以阅读。将其用于简单的条件赋值。
示例:随机决策
这个例子演示了如何使用 if...else 和随机数来做出决策:
let randomNumber = Math.random(); // 生成一个介于 0(包含)和 1(不包含)之间的数字let outcome;
if (randomNumber < 0.5) { outcome = "Heads";} else { outcome = "Tails";}
console.log(`The coin toss resulted in: ${outcome}`);// 出现 "Heads" 的概率是 50%,出现 "Tails" 的概率是 50%。