在 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敘述。
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。
在許多情況下,這能減少 nesting,讓程式碼更好閱讀、也更容易理解。
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.';
}