--- title: if...else slug: Web/JavaScript/Reference/Statements/if...else translation_of: Web/JavaScript/Reference/Statements/if...else ---
當條件成立的時候會執行 if 陳述式裡的程式,而不成立時則執行另外一個陳述式。
這個互動式的源碼被放在 GitHub 的 Repository 裡,如果您想對此互動式範例專案提出貢獻的話,請 clone https://github.com/mdn/interactive-examples 並送出 pull request。
if (條件式) statement1 [else statement2]
條件式
第一個陳述式(statement1)
第二個陳述式(statement2)
多重的 if...else
陳述式可以使用 else if
子句來建立一個巢狀結構的句子。要記住,在JavaScript中沒有 elseif
(一個單字) 的語法可以用。
if (condition1) statement1 else if (condition2) statement2 else if (condition3) statement3 ... else statementN
將巢狀結構適當的排版後,我們能更了解其背後運作的邏輯:
if (condition1) statement1 else if (condition2) statement2 else if (condition3) ...
如果在一個條件式中有多個陳述要執行,可以使用區塊陳述式({ ... }
) 把所有陳述包在一起。 通常來說,無論如何都使用區塊陳述式是個很好的習慣,尤其是當你使用巢狀結構的 if
陳述式時,這會讓人更容易理解你的程式碼。
if (condition) { statements1 } else { statements2 }
不要被Boolean物件中,布林值的 true
和 false
給混淆了。任何值只要不是 false
、 undefined
、 null
、 0
、 NaN
,或者空字串 (""
),並且任何物件,包括其值是 false
的布林物件 ,仍然會被條件陳述式視為條件成立。舉例而言:
var b = new Boolean(false); if (b) // this condition is truthy
if...else
if (cipher_char === from_char) { result = result + to_char; x++; } else { result = result + clear_char; }
else if
要記得JavaScript沒有 elseif
可以使用。不過,你可以使用 else
和 if
中間夾著空白的語法:
if (x > 5) { /* do the right thing */ } else if (x > 50) { /* do the right thing */ } else { /* do the right thing */ }
建議不要在條件表達式中直接對物件賦值,因為這會使人在瀏覽程式碼時很容易將賦值( assignment )與相等( equality )混淆。舉例而言,不要使用以下寫法:
if (x = y) { /* do the right thing */ }
如果你必須在條件表達式中使用賦值,最好ˇ的作法是以額外的括號包住賦值語句,如下所示:
if ((x = y)) { /* do the right thing */ }
Specification | Status | Comment |
---|---|---|
{{SpecName('ESDraft', '#sec-if-statement', 'if statement')}} | {{Spec2('ESDraft')}} | |
{{SpecName('ES6', '#sec-if-statement', 'if statement')}} | {{Spec2('ES6')}} | |
{{SpecName('ES5.1', '#sec-12.5', 'if statement')}} | {{Spec2('ES5.1')}} | |
{{SpecName('ES3', '#sec-12.5', 'if statement')}} | {{Spec2('ES3')}} | |
{{SpecName('ES1', '#sec-12.5', 'if statement')}} | {{Spec2('ES1')}} | Initial definition |
{{Compat("javascript.statements.if_else")}}