JS基础学习3

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>")
}
>>
hello0

hello1

hello2

hello3

hello4

hello5

hello6

hello7

hello8

hello9

  

(4)while 循环控制语句

while循环基本格式
while (条件){
语句1;
...
}
功能说明
运行功能和for类似,当条件成立循环执行语句花括号{}内的语句,否则跳出循环

 

var i=0;
while (i<10){
    document.write("<h1>hello"+i+"</h1>");
    i++;
}
>>
hello0

hello1

hello2

hello3

hello4

hello5

hello6

hello7

hello8

hello9

  

 

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");
        }

>>
hello
finally

(2)以下代码中出现未知元素x时,检测到异常,try正常运行完打印hello以后,会触发catch的运行。
        try {
            console.log("hello");
                console.log(x);
        }
        catch (e){
            console.log(e);
        }
        finally {
            console.log("finally");
        }
>>
hello
ReferenceError: x is not defined
finally

  

原文地址:https://www.cnblogs.com/asaka/p/6894994.html