Labeled Break And Continue Escape Nested Loops
A label lets continue restart the outer loop and break leave both loops at once, where an unlabeled break only exits the innermost iteration.
Code
// 有标签的 continue:直接跳到外层循环的下一轮,内层剩余迭代全部放弃
const grid = [
[1, 2, 3],
[4, 0, 6],
[7, 8, 9],
];
outer: for (const [rowIndex, row] of grid.entries()) {
for (const value of row) {
if (value === 0) {
console.log('zero in row', rowIndex, '- skip whole row');
continue outer;
}
}
console.log('row', rowIndex, 'clean:', row.join(','));
}
// 有标签的 break:一次跳出两层,而不是只退出内层
function firstNegativeRow(rows) {
let found = null;
search: for (const [i, row] of rows.entries()) {
for (const value of row) {
if (value < 0) {
found = i;
break search;
}
}
}
return found;
}
const temps = [
[3, 4],
[5, -1],
[-2, 8],
];
console.log('first negative row:', firstNegativeRow(temps));
// 无标签 break 的对照:只能退出内层,外层继续
let count = 0;
for (const row of temps) {
for (const value of row) {
if (value < 0) {
count += 1;
break;
}
}
}
console.log('unlabeled break visits rows containing negatives:', count, 'of', temps.length);Output
Captured from a sandboxed run of this snippet in the build pipeline.
row 0 clean: 1,2,3
zero in row 1 - skip whole row
row 2 clean: 7,8,9
first negative row: 1
unlabeled break visits rows containing negatives: 2 of 3How the snippet works
Labeled Break And Continue Escape Nested Loops keeps everything in the function firstNegativeRow.
Iteration is nested: for (const value of row) frames the pass, for (const row of temps) does the per-item step.
Watch out for
- The environment needs no preparation beyond having the interpreter or compiler.
Applying it
The main signature reads function firstNegativeRow(rows)
Running the file prints labeled results such as zero in row, row, first negative row: — each operation’s effect is visible in the output.
Statements that matter
let found = null;
continue outer;
let count = 0;
Interactive Tools for This Topic
Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.Regex Escape GeneratorEscape plain text so it can be embedded safely in a JavaScript RegExp, covering all metacharacters like dots, brackets, braces, and backslashes.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. The file defines `firstNegativeRow` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.