一、break
- 作用: 立刻退出当前循环体或者退出一个 switch 语句。
使用特点:
- 可以用在switch 判断语句
- 可以用在循环语句:for、for/in、for/of、do/while、while
- 不能用在 forEach、map 遍历中使用,否则会报错:Uncaught SyntaxError: Illegal break statement
1.1、break在switch分支语句中使用
const type = "first";
switch (type) {
case "first":
console.log("object");
break;
case "second":
console.log("array");
break;
case "third":
console.log("function");
break;
default:
console.log("object");
}
1.2、break在循环语句中使用
function fn() {
let arr = [1, 2, 3, 4, 5];
for (let item of arr) {
if (item === 3) {
break;
}
console.log(item);
}
}
fn();
/* 输出: */
// 1
// 2
当item === 3的时候跳出循环,所以只打印了1、2
注意:跳出的是当前循环,如果外面还有循环,外面还是会继续的
let num = 0;
for (let i = 0; i < 2; i++) {
for (let k = 1; k <= 10; k++) {
if (k % 3 == 0) {
break;
}
num++;
}
}
console.log(num); // 4
外面这一层循环,循环了两次,里面的循环每次到 k=3 就跳出里面的循环,所以打印4
二、continue
作用: continue 语句和 break 语句相似,不同的是,continue 不退出循环,只跳过本次循环。
使用特点:
- switch 判断语句
- 循环语句:for、do/while、while、for/in、for/of
- continue 不要再do/while、while 循环体中使用,会出现死循环,引起程序崩溃
function fn() {
for(var i = 0; i < 5; i++) {
if(i === 3) {
continue
}
console.log(i)
}
}
fn()
/* 输出: */
// 0
// 1
// 2
// 4
三、return
- 作用: return 用于返回函数的返回值,因此 return 语句只能出现在函数体内,否则会报错:Uncaught SyntaxError: Illegal return statement 。
使用特点:
- 只能用在 function 函数体内
- 函数中使用,函数遇到return就会立即停止执行并退出;后面可以跟函数的返回值,如果不跟就返回undefined;
- 在 for、do/while、while、for/in、for/of 中会退出循环,类似 break 的效果( break结束当前循环体、return终止函数,结束所有循环体)
- 在 forEach、map 遍历中,只跳过当前循环,会继续下次迭代,类型 continue 的效果
例1: 在 while 中当执行到 i === 3 ,会退出循环。
function fn() {
let i = 0
while (i<5) {
if (i===3) {
return
}
console.log(i)
i ++
}
}
fn()
/* 输出: */
// 0
// 1
// 2
例2: 在 forEach 循环中只跳过了 i === 2 时的这一次迭代
function fn() {
let arr = Array(5).fill(1)
arr.forEach((item, index)=>{
if (index===2) {
return
}
console.log(index)
})
}
fn()
/* 输出: */
// 0
// 1
// 3
// 4