通常在寫代碼時,您總是需要為不同的決定來執(zhí)行不同的動作。因此你需要利用條件語句來使你的程序做出正確決定并且執(zhí)行正確的動作。
JavaScript支持的條件語句用于基于不同的條件來執(zhí)行不同的動作。下面我們看一下if-else語句。
JavaScript支持如下形式的if-else語句:
if statement
if...else statement
if語句是基本的控制語句,能使JavaScript做出決定并且按條件執(zhí)行語句。
if (expression){
Statement(s) to be executed if expression is true
}
這里JavaScript expression是需要判斷的。如果返回值是true,執(zhí)行給定的 statement(s)。如果表達(dá)式的值是false ,不會執(zhí)行任何語句。多數(shù)情況下,你可能會用比較運(yùn)算符來做決定。
var age = 20;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}
程序運(yùn)行結(jié)果如下:
Qualifies for driving
if...else 語句是另一種控制語句,它能使JavaScript選擇多個代碼塊之一來執(zhí)行。
if (expression){
Statement(s) to be executed if expression is true
}else{
Statement(s) to be executed if expression is false
}
這里JavaScript expression是需要判斷的。如果返回值是true,執(zhí)行if代碼塊給定的statement(s)。如果表達(dá)式的值是false ,則執(zhí)行else代碼塊給定的statement(s)。
var age = 15;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}else{
document.write("<b>Does not qualify for driving</b>");
}
程序運(yùn)行結(jié)果如下:
Does not qualify for driving
if...else if... 語句是一種推進(jìn)形式的控制語句,它能使JavaScript選擇多個代碼塊之一來執(zhí)行。
if (expression 1){
Statement(s) to be executed if expression 1 is true
}else if (expression 2){
Statement(s) to be executed if expression 2 is true
}else if (expression 3){
Statement(s) to be executed if expression 3 is true
}else{
Statement(s) to be executed if no expression is true
}
這段代碼沒什么特別的地方。它就是一系列 if 語句,只是每個 if 語句是前一個 else 語句的一部分。語句根據(jù)正確的條件被執(zhí)行,如果不滿足任何一個條件則執(zhí)行 else 代碼塊。
var book = "maths";
if( book == "history" ){
document.write("<b>History Book</b>");
}else if( book == "maths" ){
document.write("<b>Maths Book</b>");
}else if( book == "economics" ){
document.write("<b>Economics Book</b>");
}else{
document.write("<b>Unknown Book</b>");
}
程序運(yùn)行結(jié)果如下:
Maths Book
更多建議: