众所周知,javascript 是运行在单线程的,主线程的代码无法中断执行,否则整个应用就跑不起来了,比如在全局执行环境使用 return 语句

let a = 1;
console.log(1);
if (a == 1) {
return;
}
console.log(2);

控制台直接报错 Uncaught SyntaxError: Illegal return statement,想要解决上述的逻辑,可以通过一个函数包裹起来,让代码运行在函数执行环境里运行。

foo();
function foo() {
let a = 1;
console.log(1);
if (a == 1) {
return;
}
console.log(2);
}

return 只能中断当前执行函数的执行,不能中断外部函数的执行,比如下面的代码会输出 continue 因为 forEach 执行的是每个回调函数,return 无法在外部函数返回

function foo() {
[1, 2, 3].forEach((item) => {
if (item == 1) {
return;
}
});
console.log('continue');
}
foo();

上面可以使用 for 或者 for in 来解决,由于都是同步代码,所以可以 return 来中断

function foo() {
for (let i in [1, 2, 3]) {
if (i == 1) {
return;
}
}
console.log('continue');
}
foo();

label 标记语句

MDN 对 label 标记语句的定义,可使用一个标签来唯一标记一个循环,然后使用 break 或 continue 语句来指示程序是否中断或继续执行。

需要注意的是 JavaScript 没有 goto 语句,标记只能和 break 或 continue 一起使用。

在严格模式中,你不能使用“let”作为标签名称。它会抛出一个 SyntaxError(let 是一个保留的标识符)。

var i, j;
outer: for (i = 0; i < 3; i++) {
// 外部循环
inner: for (j = 0; j < 3; j++) {
// 内部循环
if (i == 1 && j == 1) {
continue outer;
}
console.log('i = ' + i + ', j = ' + j);
}
}

我们也可以使用 label 标记语句来实现中断代码

function foo(a) {
foo: {
if (a == 100) {
break foo;
}
console.log(a);
}
}
foo(1); // console.log(1);
foo(100); // 无打印

try/catch

使用 try/catch 也可以实现代码中断执行

foo(1);
foo(100);
function foo(a) {
try {
if (a == 100) {
// 中断
throw new Error('break execute');
}
console.log('continue execute');
} catch (err) {
console.log(err);
}
}