if... else語句是JavaScript條件語句之一,用于根據(jù)不同的條件執(zhí)行不同的操作。
在JavaScript中,我們具有以下條件語句:
if指定的條件為true,則使用if指定要執(zhí)行的代碼塊
如果相同條件為false,則使用else來指定要執(zhí)行的代碼塊
如果第一個(gè)條件為false,則使用else if指定要測(cè)試的新條件
使用switch從要執(zhí)行的許多代碼塊中選擇一個(gè)
if條件為true,則if語句指定要執(zhí)行的代碼塊:
if (condition) {
//如果條件為true,則執(zhí)行的代碼塊
}else語句指定如果條件是false的要執(zhí)行的代碼塊:
if (condition) {
//如果條件為true,則執(zhí)行的代碼塊
} else {
//如果條件為false,則執(zhí)行的代碼塊
}eelse if語句指定了一個(gè)新的條件,如果第一個(gè)條件為false:
if (condition1) {
//如果條件1為true,則執(zhí)行的代碼塊
} else if (condition2) {
//如果條件1為假而條件2為true,則執(zhí)行的代碼塊
} else {
//如果條件1和條件2為false,則執(zhí)行的代碼塊
}var x = -4;
if (x < 0) {
document.getElementById("result").innerHTML = "NEGATIVE";
}測(cè)試看看?/?所有瀏覽器完全支持if ... else語句:
| Statement | ![]() | ![]() | ![]() | ![]() | ![]() |
| if...else | 是 | 是 | 是 | 是 | 是 |
| 參數(shù) | 描述 |
|---|---|
| condition | 計(jì)算結(jié)果為true或false的表達(dá)式 |
| JavaScript版本: | ECMAScript 1 |
|---|
如果變量x的值小于0,則輸出“ NEGATIVE”,否則輸出“ POSITIVE”:
var x = -4;
if (x < 0) {
msg = "NEGATIVE";
} else {
msg = "POSITIVE";
}測(cè)試看看?/?如果x等于10,則寫“ x為10”,如果不等于,但x等于20,則寫“ x為20”,否則寫為“ x不存在”:
var x = 20;
if (x === 10) {
document.write("x 為 10");
} else if (x === 20) {
document.write("x 為 20");
} else {
document.write("x不存在");
}測(cè)試看看?/?您可以使用多個(gè)else if語句:
// 設(shè)置學(xué)生的當(dāng)前成績(jī)
var grade = 88;
//檢查成績(jī)是否為A,B,C,D或F
if (grade >= 90) {
document.write("A");
} else if (grade >= 80) {
document.write("B");
} else if (grade >= 70) {
document.write("C");
} else if (grade >= 60) {
document.write("D");
} else {
document.write("F");
}測(cè)試看看?/?您可以編寫不帶花括號(hào)的單行語句:
var x = -4; if (x < 0) msg = "NEGATIVE"; else msg = "POSITIVE";測(cè)試看看?/?
如果用戶單擊圖像,請(qǐng)更改圖像的src屬性的值:
<img id="demo" onclick="changeImage()" src="avatar-female.jpg">
<script>
function changeImage() {
var image = document.getElementById("demo");
if (image.src.match("female")) {
image.src = "avatar-male.jpg";
} else {
image.src = "avatar-female.jpg";
}
}
</script>測(cè)試看看?/?使用if ... else語句驗(yàn)證輸入數(shù)據(jù):
function myFunc(x) {
var text;
//如果x不是一個(gè)數(shù)字,或者小于10,或者大于20,輸出“Input not valid”
//如果x是10到20之間的數(shù)字,則輸出“Input OK”
if (isNaN(x) || x < 10 || x > 20) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("result").innerHTML = text;
}測(cè)試看看?/?嵌套if ... else語句:
var a = 10, b = 20, c = 30;
var answer;
if (a > b) {
if (a > c) {
answer = "A is the greatest among three";
} else {
answer = "C is the greatest among three";
}
} else if (b > c) {
answer = "B is the greatest among three";
} else {
answer = "C is the greatest among three";
}測(cè)試看看?/?JavaScript教程:JavaScript If... Else語句
JavaScript教程:JavaScript switch