一、if else 条件判断
if(条件表达式)
//如果条件表达式为true,执行此处的语句
}else{
//如果条件表达式为false,执行此处的语句
}
if(1){ console.log( true ); }else{ console.log( false ); }//true
注意:条件表达式最后都转化成布尔型,0表示false,大于等于1表示true。
- 字符串有空格和无空格
var i='king'; var j='king ';//空格区别 if(i==j){ document.write('hello king'); }else{ document.write('hello nana'); }//输出:hello nana
- if条件判断可以省略大括号({})
- 如果条件判断为true,则条件判断后的语句都为true的执行语句
- 如果条件判断为false,则从条件判断后第二句开始都为false的执行语句
if(3>11)
document.write('hello ');
document.write('world ');
document.write('world ');
if(3<11) document.write('当成true执行'); document.write('当成else执行 '); document.write('当成else执行 '); //最后输出:当成else执行 当成else执行
- 如果if里执行语句有var定义变量
- 可以读出声明的变量,但读不出变量里存的值
if(true){ var x=1,y=2,username='king'; } alert(x);//弹出undefined
二、if else if条件判断
if(条件判断){ 执行语句...
}else if( 条件判断){ 执行语句...
}else if( 条件判断){ 执行语句...
}else{执行语句...}
var x=11; if(x==1){ document.write('aaa'); }else if(x==2){ document.write('bbb'); }else if(x==3){ document.write('ccc'); }else{ document.write('以上表达式都为false执行的代码段'); }//输出:以上表达式都为false执行的代码段
三、if else 条件嵌套
if(条件判断){
if(条件判断){
if(条件判断){
}else{
执行语句...
}
}else{
执行语句...
}
}else{
执行语句...
}
var username='king',age=22,sex='男'; if(3>1){ document.write('aa<br/>'); if(username=='king'){ document.write('hello King<br/>'); if(age>=18){ document.write('成年人<br/>'); if(sex=='男'){ document.write('帅哥'); }else{ document.write('美女'); } }else{ document.write('未成年'); } }else{ document.write('hello others<br/>'); } }else{ document.write('bb<br/>'); }//输出:aa
hello King
成年人
帅哥
- 技巧:如何缩进不清楚,不清楚那个if对应哪个else.可以找第一个else,上面最近的一个if和此时的else对应。依次找出if对应的else.
四、switch case判断
switch(表达式){
case 表达式1:语句1;
case 表达式2:语句2;
case 表达式3:语句3;
default:语句;
}
- 表达式和满足表达式的数据类型相等
- 如果表达式满足条件,执行语句后没有遇到break,则会继续执行满足条件后的所有语句;
- 如果表达式的满足条件在最后一条,可以不写跳出循环break。
- 如果表达式没有满足条件的语句,则执行default语句。
var i=14; switch(i){ case 1: document.write('a'); case 2: document.write('b'); default: document.write('e'); case 3: document.write('c'); break; case 4: document.write('d'); }//输出结果是:ec