← 中文资源

简体中文版本

带标签的 break 与 continue 跳出嵌套循环

标签让 continue 直接跳到外层下一轮、break 一次跳出两层循环;不带标签的 break 只能退出最内层,外层照常继续,嵌套扫描时省掉额外的状态变量。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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 3

实现说明

底层就是函数 firstNegativeRow。 核心工作在嵌套循环里完成:外层 for (const value of row),内层 for (const row of temps)。

使用要点

  • 直接运行文件,输出会带上标签,比如 zero in row、row、first negative row:——输出的每一行都能指回产生它的那次调用。

常见问题

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 文件在加载时定义 firstNegativeRow。

签名一览:function firstNegativeRow(rows)

核心语句

let found = null;
continue outer;
let count = 0;

代码示例

// 有标签的 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);