WEB基礎之:JavaScript條件語句
阿新 • • 發佈:2021-01-07
JavaScript條件語句
1. if … else 語句
1.1 基本的的 if…else 語法
//寫法一:
if (condition) {
code to run if condition is true
} else {
run some other code instead
}
//寫法二:
if (condition) {
code to run if condition is true
}
run some other code
//寫法三:
if (condition) code to run if condition is true
else run some other code instead
1.2 巢狀if … else
if (condition) {
code to run if condition is true
} else if(condition) {
code to run if condition is true
} else {
run some other code instead
}
2. switch語句
switch (expression) {
case choice1:
run this code
break;
case choice2:
run this code instead
break;
// include as many cases as you like
default:
actually, just run this code
}
//default 部分不是必須的,通過它來處理未知的情況。
3. 三元運算子
( condition ) ? run this code : run this code instead
( select. value === 'black' ) ? update('black','white') : update('white','black');
//它以測試條件開始select.value === 'black'。如果返回true,執行update()帶有黑色和白色引數的函式.
//如果返回false,我們執行update()帶有白色和黑色引數的函式。