if...else
试一试
function testNum(a) {
let result;
if (a > 0) {
result = "positive";
} else {
result = "NOT positive";
}
return result;
}
console.log(testNum(-5));
// Expected output: "NOT positive"
语法
js
if (condition)
statement1
// With an else clause
if (condition)
statement1
else
statement2
描述
多个 if...else 语句可以嵌套以创建 else if 子句。请注意,JavaScript 中没有 elseif(一个词)关键字。
js
if (condition1)
statement1
else if (condition2)
statement2
else if (condition3)
statement3
// …
else
statementN
为了了解其工作原理,如果正确缩进,它看起来会是这样
js
if (condition1)
statement1
else
if (condition2)
statement2
else
if (condition3)
statement3
// …
要在子句中执行多个语句,请使用块语句({ /* ... */ })来分组这些语句。
js
if (condition) {
statements1
} else {
statements2
}
不使用块可能会导致令人困惑的行为,特别是如果代码是手动格式化的。例如
js
function checkValue(a, b) {
if (a === 1)
if (b === 2)
console.log("a is 1 and b is 2");
else
console.log("a is not 1");
}
这段代码看起来很无辜——然而,执行 checkValue(1, 3) 会输出“a is not 1”。这是因为在悬空 else 的情况下,else 子句将连接到最近的 if 子句。因此,上面的代码,如果正确缩进,看起来会是这样
js
function checkValue(a, b) {
if (a === 1)
if (b === 2)
console.log("a is 1 and b is 2");
else
console.log("a is not 1");
}
通常,始终使用块语句是一个好习惯,尤其是在涉及嵌套 if 语句的代码中。
js
function checkValue(a, b) {
if (a === 1) {
if (b === 2) {
console.log("a is 1 and b is 2");
}
} else {
console.log("a is not 1");
}
}
不要将原始布尔值 true 和 false 与 Boolean 对象的真值或假值混淆。任何不是 false、undefined、null、0、-0、NaN 或空字符串("")的值,以及任何对象,包括值为 false 的布尔对象,在用作条件时都被认为是真值。例如
js
const b = new Boolean(false);
if (b) {
console.log("b is truthy"); // "b is truthy"
}
示例
使用 if...else
js
if (cipherChar === fromChar) {
result += toChar;
x++;
} else {
result += clearChar;
}
使用 else if
请注意,JavaScript 中没有 elseif 语法。但是,您可以在 else 和 if 之间留一个空格来编写它
js
if (x > 50) {
/* do something */
} else if (x > 5) {
/* do something */
} else {
/* do something */
}
使用赋值作为条件
您几乎不应该将带有赋值(如 x = y)的 if...else 作为条件
js
if ((x = y)) {
// …
}
因为与 while 循环不同,条件只评估一次,所以赋值也只执行一次。上面的代码等价于
js
x = y;
if (x) {
// …
}
这样更清晰。但是,在极少数情况下,如果您发现自己想要这样做,while 文档有一个将赋值作为条件部分,其中包含我们的建议。
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-if-statement |
浏览器兼容性
加载中…