if 指令有以下多種組合:
- if (條件式) 單一指令;
條件式的結果為 true 時,會執行後接的單一指令;否則跳過,不執行。
- 程式用法:
<script type='text/javascript'>
a=9;
if( a>8 ) document.write('大');
</script> - 執行結果:
大
條件式通常為邏輯計算式,其結果為布林值:true, false。但是數值 0 也被當成 false,非 0 數值則是 true;所以條件式也可以是一般計算式。
- 程式用法:
<script type='text/javascript'>
if( a-7 ) document.write('非 0 數值');
</script> - 執行結果:
非 0 數值
- 程式用法:
- if (條件式) {多個指令;}
條件式後面可以接一個區塊{ },內有多個指令。條件式的結果為 false 時,整個區塊會被跳過 。
- 程式用法:
<script type='text/javascript'>
if(a>7)
{
a+=7;
document.write(a);
}
</script> - 執行結果:
16
- 程式用法:
- if (條件式) 指令一; else 指令二;
if 可以接 else。條件式的結果為 true 時,執行指令一;否則執行指令二。指令一,指令二都 可以用區塊取代。
- 程式用法:
<script type='text/javascript'>
if(a>20)
{
document.write('大');
}
else
document.write('小');
</script> - 執行結果:
小
- 程式用法:
- if (條件式一) 指令一; else if (條件式二) 指令二;
if else 之後可以接 if,可以接多層 else if。如此可以檢測多個條件式,只有遇到第一個為 true 的條件式,其後的指令會被執行。也有可能所有的條件式都不合,所有指令都被跳過。使用 if else if 有時太多層,閱讀會有點混淆;可以加上區塊{ },閱讀起來,比較分明。
- 程式用法:
<script type='text/javascript'>
if(a<10) document.write('小於 10');
else if( a<20 ) document.write('小於 20');
else if( a<30 ) document.write('小於 30');
</script> - 執行結果:
小於 20
- 程式用法: