คำสั่ง if...else if... เป็นรูปแบบขั้นสูงของ 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…else if คำสั่งใน 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>