SyntaxError: unlabeled break must be inside loop or switch
当一个 break 语句不在循环或 switch 语句中时,会发生 JavaScript 异常 "unlabeled break must be inside loop or switch"。
消息
SyntaxError: Illegal break statement (V8-based) SyntaxError: unlabeled break must be inside loop or switch (Firefox) SyntaxError: 'break' is only valid inside a switch or loop statement. (Safari)
错误类型
哪里出错了?
break 语句可用于退出循环或 switch 语句,在其他地方使用它们是语法错误。或者,您可以为 break 语句提供一个 标签,以跳出带有该标签的任何语句——但是,如果该标签没有引用包含语句,则会抛出另一个错误 SyntaxError: label not found。
示例
非语法的 break
break 不能在 switch 或循环之外使用。
js
let score = 0;
function increment() {
if (score === 100)
break; // SyntaxError: unlabeled break must be inside loop or switch
}
score++;
}
也许您打算使用 return 来提前终止函数,而不是 break。
js
let score = 0;
function increment() {
if (score === 100) {
return;
}
score++;
}
在回调中使用 break
break 不能在回调中使用,即使回调是从循环中调用的。
js
let containingIndex = 0;
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
while (containingIndex < matrix.length) {
matrix[containingIndex].forEach((value) => {
if (value === 5) {
break; // SyntaxError: unlabeled break must be inside loop or switch
}
});
containingIndex++;
}
相反,重构代码,使 break 在回调之外使用。
js
let containingIndex = 0;
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
outer: while (containingIndex < matrix.length) {
for (const value of matrix[containingIndex]) {
if (value === 5) {
break outer;
}
}
containingIndex++;
}
js
let containingIndex = 0;
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
while (containingIndex < matrix.length) {
if (matrix[containingIndex].includes(5)) {
break;
}
containingIndex++;
}
无法提前终止 forEach() 循环。您可以改用 some(),或者将其转换为 for...of 循环。
js
array.forEach((value) => {
if (value === 5) {
break; // SyntaxError: unlabeled break must be inside loop or switch
}
// do something with value
});
js
array.some((value) => {
if (value === 5) {
return true;
}
// do something with value
return false;
});
js
for (const value of array) {
if (value === 5) {
break;
}
// do something with value
}