JS基礎學習3

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.