1.if條件
此條件語句只有當它指定條件為true的時候才會執(zhí)行操作。
語法:
if (condition)
{
當條件為 true 時執(zhí)行的代碼
}
這里注意要使用小寫的 if。使用大寫字母(IF)會生成 JavaScript 錯誤!
例如:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>if語句</title>
</head>
<body>
<p>如果時間早于 20:00,會獲得問候 "Good day"。</p>
<button onclick="myFunction()">點擊這里</button>
<p id="demo"></p>
<script>
function myFunction(){
var x="";
var time=new Date().getHours();
if (time<20){
x="Good day";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>
注意,在這個語法中,沒有 else。我已經(jīng)告訴瀏覽器只有在指定條件為 true 時才執(zhí)行代碼。
2.switch
switch可以執(zhí)行多個代碼塊
語法
switch(n)
{
case 1:
執(zhí)行代碼塊 1
break;
case 2:
執(zhí)行代碼塊 2
break;
default:
n 與 case 1 和 case 2 不同時執(zhí)行的代碼
}
首先設(shè)置表達式 n(通常是一個變量)。隨后表達式的值會與結(jié)構(gòu)中的每個 case 的值做比較。如果存在匹配,則與該 case 關(guān)聯(lián)的代碼塊會被執(zhí)行。使用 break 來阻止代碼自動地向下一個 case 運行。