WEB基础之: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()带有白色和黑色参数的函数。
posted @ 2021-01-06 23:33  f_carey  阅读(5)  评论(0编辑  收藏  举报  来源