2011年11月19日 星期六

JavaScript 的 if 判斷式

流程控制 (Flow Control)

一個程式未必一定要由上到下執行的,我們可以跟據一些條件來控制一個程式執行那一個部份,亦即是控制它的流程。

if語法:
if (condition) {
statements
}

//如果只有一句敘述,就可以不用大括號包起來:
if (condition) statement ;


condition true 時,就執行 statements ,否則,跳過 if 的範圍(即是大括號範圍或僅有一句敘述後之分號範圍)。
程式範例(if):
<script>
var num_student = 2;
if (num_student > 1) {
document.write("There are ");
document.write(num_student);
document.write(" students.");
}
if (num_student == 1) {
document.write("There is one student.");
}
</script>



if...else語法:

if (condition) {
statements1
}
else {
statements2
}

//如果 if 和 else 都只有一句敘述,就可以不用大括號包起來:
if (condition) statement1 ;
else statement2 ;


當 condition 是 true 時,就執行 statements1 ,然後跳過 else 範圍,否則,就執行 statements2。



程式範例(if ... else):
<script>
var num_student = 1;
if (num_student == 0) {
document.write("There are no student");
}
else {
document.write("There is at least one student.");
}
</script>

1 則留言:

  1. 請問

    IF 判斷是 是否可以包含 多個判斷
    例如
    if ( eval(document.getElementById("H").value) == "" && eval(document.getElementById("I").value) == "")

    回覆刪除