为什么标签在不与循环一起使用时不起作用

Why JS lables does'nt work when not used with loops

我在这里写了一个小的JS代码。运行没有任何错误

repeat:
  while(true){
    console.log('Start');
    break repeat;
    console.log('End');
  }

但是当我不使用 while 语句时,程序会抛出错误 Undefined label repeat

repeat:
    console.log('Start');
    break repeat;
    console.log('End');

为什么程序会抛出那个错误?标签只用于循环吗?

基本上,它适用于代码 blocks。虽然您没有任何要打破的块,但代码会抛出错误。

repeat: {
    console.log('Start');
    break repeat;
    console.log('End');
}

此外,"such a construct is basically a goto in drag." 我更希望看到用 continue 语句编写的逻辑,如下所示:

while (true) {
  console.log('start');
  if (x == y) continue;
  console.log('foo');
  if (q != z) continue;
  ...
}

我的观点是 "it's still a while loop, just as I said it would be," 除了它并不总是到达终点。当它没有到达终点时,它总是回到顶部。

break 语句在 while (true) 的情况下最常见,事实上,阅读您的代码的任何其他人都希望如此。逻辑运行直到满足某些条件,此时它 "breaks out of the loop" 并转到它后面的语句。

当您“break 喜欢 goto”时,您的逻辑就变得更加难以理解和理解。这是一个非常重要的考虑因素。 "Write simply and clearly, and in the way that is customarily expected. Don't throw a curve-ball."