如果 Else If Else Control
在最簡單的形式中,可以使用 if 條件,如下所示:
var i = 0;
if (i < 1) {
console.log("i is smaller than 1");
}
評估條件 i < 1,如果評估為 true,則執行後面的塊。如果它評估為 false,則跳過該塊。
if 條件可以擴充套件 if 條件。如上所述檢查條件一次,並且如果它評估為 false,則將執行二級塊(如果條件是 true 則將跳過該二級塊)。一個例子:
if (i < 1) {
console.log("i is smaller than 1");
} else {
console.log("i was not smaller than 1");
}
假設 else 塊只包含另一個 if 塊(可選擇一個 else 塊),如下所示:
if (i < 1) {
console.log("i is smaller than 1");
} else {
if (i < 2) {
console.log("i is smaller than 2");
} else {
console.log("none of the previous conditions was true");
}
}
然後還有一種不同的寫入方式可以減少巢狀:
if (i < 1) {
console.log("i is smaller than 1");
} else if (i < 2) {
console.log("i is smaller than 2");
} else {
console.log("none of the previous conditions was true");
}
關於上述例子的一些重要腳註:
-
如果任何一個條件被評估為
true,則不會評估該塊鏈中的其他條件,並且將不執行所有相應的塊(包括else塊)。 -
else if部件的數量幾乎是無限的。上面的最後一個例子只包含一個,但你可以擁有任意多個。 -
if語句中的條件可以是任何可以強制轉換為布林值的條件,有關詳細資訊,請參閱布林邏輯主題 ; -
if-else-if梯子在第一次成功時退出。也就是說,在上面的例子中,如果i的值是 0.5,則執行第一個分支。如果條件重疊,則執行執行流程中出現的第一個標準。另一個條件,也可能是真的被忽略了。 -
如果你只有一個語句,那個語句周圍的大括號在技術上是可選的,例如這很好:
if (i < 1) console.log("i is smaller than 1");這也可行:
if (i < 1) console.log("i is smaller than 1");如果你想在
if塊中執行多個語句,那麼它們周圍的花括號是必需的。僅使用縮排是不夠的。例如,以下程式碼:if (i < 1) console.log("i is smaller than 1"); console.log("this will run REGARDLESS of the condition"); // Warning, see text!相當於:
if (i < 1) { console.log("i is smaller than 1"); } console.log("this will run REGARDLESS of the condition");