標籤:try 格式 pytho reference 語句 括弧 迴圈 就會 ida
1.控制語句
(1)if控制語句
if-else基本格式if (運算式){語句1;......}else{語句2;.....}功能說明如果運算式的值為true則執行語句1,否則執行語句2
if(0>2){
console.log("success!")
}else{
console.log("failure")
}
>>
failure
(2)switch選擇控制語句
switch基本格式switch (運算式) { case 值1:語句1;break; case 值2:語句2;break; case 值3:語句3;break; default:語句4;}
x=2;
switch (x){
case 0:console.log("Sunday");break;
case 1:console.log("Monday");break;
case 2:console.log("Tuesday");break;
case 3:console.log("周三");break;
case 4:console.log("周四");break;
case 5:console.log("Friday");break;
case 6:console.log("周六");break;
default :console.log("未定義");
}
>>
Tuesday
(3)for 迴圈控制語句
for迴圈基本格式for (初始化;條件;增量){語句1;...}功能說明實現條件迴圈,當條件成立時,執行語句1,否則跳出迴圈體
for(var i=0;i<10;i++){
document.write("<h1>hello"+i+"</h1>")
}
>>hello0hello1hello2hello3hello4hello5hello6hello7hello8hello9
(4)while 迴圈控制語句
while迴圈基本格式while (條件){語句1;...}功能說明運行功能和for類似,當條件成立迴圈執行語句花括弧{}內的語句,否則跳出迴圈
var i=0;
while (i<10){
document.write("<h1>hello"+i+"</h1>");
i++;
}
>>
hello0hello1hello2hello3hello4hello5hello6hello7hello8hello9
2.異常處理
try { //這段代碼從上往下運行,其中任何一個語句拋出異常該代碼塊就結束運行}catch (e) { // 如果try代碼塊中拋出了異常,catch代碼塊中的代碼就會被執行。 //e是一個局部變數,用來指向Error對象或者其他拋出的對象}finally { //無論try中代碼是否有異常拋出(甚至是try代碼塊中有return語句),finally代碼塊中始終會被執行。}
(1)正常情況下,沒有異常,是不會觸發catch的啟動並執行 try { console.log("hello"); } catch (e){ console.log(e); } finally { console.log("finally"); }>>hellofinally(2)以下代碼中出現未知元素x時,檢測到異常,try正常運行完列印hello以後,會觸發catch的運行。 try { console.log("hello"); console.log(x); } catch (e){ console.log(e); } finally { console.log("finally"); }>>helloReferenceError: x is not definedfinally
JS基礎學習3