條件語(yǔ)句
- if(條件){語(yǔ)句1;}else{語(yǔ)句2;}
條件為true蝗碎,則取語(yǔ)句1堪旧,false則取語(yǔ)句2.
<script>
var isMale=true;//可寫(xiě)表達(dá)式,如4>3
if(isMale){
document.write('男');
document.write('hello')
}else{
document.write('女');
}//else可不寫(xiě),則false時(shí)不執(zhí)行操作
</script> - if(條件1){語(yǔ)句1;} else if(條件2){語(yǔ)句2;} else{語(yǔ)句3;}
可以有多個(gè)條件
var score=50;
if(score>=80){
document.write('A');
}else if(score>=70){
document.write('B');
}else if(score>=60){
document.write('C');
}else{
document.write('D');} - switch(表達(dá)式){
case1:語(yǔ)句;break;
case2:語(yǔ)句;break婴谱;
default:語(yǔ)句;break;}
var degree='B'{
switch(degree){
case'A':
document.write('優(yōu)秀');
break躯泰;
case'B':
document.write('良好');
break谭羔;
case'C':
document.write('及格');
break;
default:
document.write('不及格');
}
循環(huán)語(yǔ)句
while(表達(dá)式){語(yǔ)句麦向;}
do{語(yǔ)句}while(表達(dá)式)先執(zhí)行一遍語(yǔ)句瘟裸,再判斷循環(huán)
var i=11;
do{
document.write(i);
i++;
}
while(i<=10)for(初始化;循環(huán)條件诵竭;更新表達(dá)式){語(yǔ)句;}
for(var i=1;i<10;i++){
document.write(i);
}break跳出整個(gè)循環(huán)
-
continue跳出當(dāng)前循環(huán)话告,繼續(xù)執(zhí)行其他循環(huán)
for(var i=1;i<10;i++){
if(i==5){break}
document.write(i);
}//1234for(var i=1;i<10;i++){ if(i==5){continue} document.write(i); }//12346789
for(屬性名in對(duì)象){語(yǔ)句}
var cat={
name:"kitty"
age:2
mew:function(){
console.log(喵喵喵)兼搏;}
}
for(var p in cat){
document.write(p);
}//name age mew
with語(yǔ)句
with(表達(dá)式){語(yǔ)句;}
把語(yǔ)句的作用域指向到某個(gè)對(duì)象沙郭,對(duì)同一個(gè)對(duì)象有多次操作時(shí)佛呻,可簡(jiǎn)化代碼
異常捕獲語(yǔ)句
- try{語(yǔ)句;}catch(exception){語(yǔ)句棠绘;}finally{語(yǔ)句件相;}
try語(yǔ)句出錯(cuò)時(shí)會(huì)被catch捕捉
try{
document.write(notDefined)
}catch(error){
alter(error);{
finally{
alter(finally)
}//ReferenceError:...
//finally