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
}