在 JavaScript 中,按条件执行逻辑的一种常见方式是使用if语句。
它由if关键字、包裹在圆括号中的条件,以及包裹在大括号中的代码块组成。
只有当条件的求值结果为true时,代码块才会执行。
if (condition) {
// code that is executed if "condition" is true
}
它既可以单独使用,也可以与else关键字组合使用。
if (condition) {
// code that is executed if "condition" is true
} else {
// code that is executed otherwise
}
if语句要在else语句中嵌套另一个条件,可以使用else if。
注意,JavaScript 中没有elseif关键字。
而要先写else,再跟一个if语句。
if (condition1) {
// code that is executed if "condition1" is true
} else if (condition2) {
// code that is executed if "condition2" is true
// but "condition1" was false
} else {
// code that is executed otherwise
}
理论上,你可以嵌套任意数量的附加条件。
但在实际中,这些情况下你会改用 switch statement。
if (condition1) {
// ...
} else if (condition2) {
// ...
} else if (condition3) {
// ...
} else if (condition4) {
// ...
} else {
// ...
}
在构造复杂条件时,请参考运算符优先级表,以避免不必要的括号。
if (num >= 0 && num < 1) {
// ...
}
// The inner brackets are obsolete because relational operators
// have higher precedence than logical operators.
<!-- prettier-ignore-start -->
if ((num >= 0) && (num < 1)) {
// ...
}
<!-- prettier-ignore-end -->
此外,可以考虑使用额外的变量,让代码更易读。
const isPositive = num >= 0;
const isSmall = num < 1;
if (isPositive && isSmall) {
// ...
}
在 JavaScript 中,条件不一定是布尔类型。
如果在if语句这样的布尔上下文中提供的不是布尔类型,JavaScript 会隐式地把该值转换为布尔值。
至于哪些值是 truthy、哪些是 falsy,详见类型转换概念。
const num = 4;
if (num) {
// this code block will be executed because 4 is truthy
}
如果你只想在if或else的代码块中执行一条语句,JavaScript 允许省略大括号。
if (condition) doSomething();
// or
if (condition)
doSomething();
例如,在检查错误条件时有时会这样写。 但总体来说,不推荐这样做,因为当你再添加一条应当依赖同一条件的语句时,很容易忘记把括号加回去。
在编写函数时,一种常见的写法是省略else代码块,改为在if代码块中提前return。
在很多情况下,这样可以减少_嵌套_,让代码更易读、更容易理解。
function checkNumber(num) {
let message = '';
if (num === 0) {
message = 'You passed 0, please provide another number.';
} else {
message = 'Thanks for passing such a nice number.';
}
return message;
}
// Can also be written as ...
function checkNumber(num) {
if (num === 0) {
return 'You passed 0, please provide another number.';
}
return 'Thanks for passing such a nice number.';
}