JavaScript中的if ... else if ...语句是什么?
if...elseif...语句是if...else的高级形式,它使JavaScript可以从多个条件中做出正确的决定。
语法
if-else-if语句的语法如下-
if (expression 1){
Statement(s) to be executed if expression 1 is true
}
else if (expression2){
Statement(s) to be executed if expression 2 is true
}
else if (expression3){
Statement(s) to be executed if expression 3 is true
}
else{
Statement(s) to be executed if no expression is true
}示例
您可以尝试运行以下命令,以了解如何使用if…elseif语句在JavaScript中进行处理-
<html>
<body>
<script>
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>EconomicsBook</b>");
}
else{
document.write("<b>Unknown Book</b>");
}
</script>
</body>
<html>