关键字break,continue和return的用法及区别

continue用于for(结合if语句使用),for…in,while,do…while循环体中。
break用于for(结合if语句使用),for…in,while,do…while循环体中,或用于switch语句中。
return 是函数返回语句,但是返回的同时也将函数停止。
相同之处:三个都会将语句停止。
不同之处:
1、当 break 语句用于 switch 语句中时,会跳出 switch 代码块,终止执行代码。
当 break 语句用于循环语句时,会跳出循环,并执行循环后代码(如果有的话)。
2、continue:结束当前循环,后面的循环继续执行。
3、return :停止函数。

注意点

1.函数中写了return之后,后面的代码都不会再执行

function a(){
    
    
    for (var i = 0; i < 5; i++) {
    
    
         if (true) {
    
    
         //只要满足条件则跳出整个循环,并且循坏外的代码也不执行
            return false
         }
    };
    return true
}
let res = a()    //fasle

2.b函数调用a函数,a函数中的return,并不影响b函数中后面代码的执行

function b(){
    
    
    a()
    console.log("b执行了");  //b执行了
}
b()

3.swicth中如果想要return,需写在函数中,且不要写break

function c() {
    
    
    let num = 10
    switch (num) {
    
    
        case (10):
            return "c执行了";
        // break;
        default:
            return 1;
        // break;
    }
}
let foo = c()
console.log(foo);

猜你喜欢

转载自blog.csdn.net/m0_48076809/article/details/110121594
今日推荐