Javascript中的break关键字仅用于跳出循环吗?

发布于 2025-01-03 09:18:15 字数 1110 浏览 0 评论 0原文

我的一位朋友正在教授 Javascript 编程课程,他的作业之一是创建一个猜数字游戏。这是他的示例实现:

funProgram: for(;;) {
  numberGuesser: {
    var num = (Math.random() * 100) | 0;
    var guess = +prompt("I'm thinking of a number between 0 and 100. Try to guess it.", 0);
    var guesses = 1;
    guess: for(;;) {
      higher: {
        lower: {
          if(guess === num) break guess;
          if(guess > num) break lower;
          guess = +prompt("Too low. Try again.", 0);
          break higher;
        }
        guess = +prompt("Too high. Try again.", 0);
      }
      guesses++;
    }
    alert("You got it in " + guesses + " guesses! The number is " + num);
  }
  var again = prompt("Do you want to guess again (y/n)?", "y") === "y";
  if(!again) break funProgram;
}

他告诉我,标记代码并在代码周围包裹块是一个很好的做法,这样您就可以轻松地看到每个部分在做什么。他还表示,带标签的中断和继续比未标记的更容易阅读,因为你可以准确地知道你要中断什么。我从未见过这样的代码模式,所以我不确定这是否属实。

我使用 Javascript 一段时间了,这里有一些我以前从未见过的东西,还有一些我仍然不明白的东西。我认为 break 关键字专门用于跳出循环。 higherlower 块不是循环,但显然您仍然可以打破它。这怎么可能?对我来说,打破不循环的东西似乎很奇怪。您还可以使用 break 关键字来中断函数吗?

One of my friends is teaching a programming class with Javascript and one of his assignments was to create a number guessing game. This was his example implementation:

funProgram: for(;;) {
  numberGuesser: {
    var num = (Math.random() * 100) | 0;
    var guess = +prompt("I'm thinking of a number between 0 and 100. Try to guess it.", 0);
    var guesses = 1;
    guess: for(;;) {
      higher: {
        lower: {
          if(guess === num) break guess;
          if(guess > num) break lower;
          guess = +prompt("Too low. Try again.", 0);
          break higher;
        }
        guess = +prompt("Too high. Try again.", 0);
      }
      guesses++;
    }
    alert("You got it in " + guesses + " guesses! The number is " + num);
  }
  var again = prompt("Do you want to guess again (y/n)?", "y") === "y";
  if(!again) break funProgram;
}

He told me that it's a good practice to label your code and wrap blocks around it so you can easily see what each section is doing. He also said labeled breaks and continues are much easier to read than unlabeled ones because you can know exactly what you are breaking out of. I've never seen any code patterns like this, so I'm not sure if this is true.

I've been using Javascript for a while and there are a few things in here that I've never seen before and some things that I still don't understand. I thought that the break keyword was specifically meant for breaking out of loops. The higher and lower blocks are not loops, but apparently you can still break out of it. How is that possible? It seems odd to me to break out of something that doesn't loop. Can you also break out of functions using the break keyword?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

沩ん囻菔务 2025-01-10 09:18:15

中断实际上可以有标签(并接受它们)。然而,我不确定“他”是谁,但我什至可以说“他”传达的是他的编程理想,而不是特定的标准。也就是说,没有必要使用标签,它只是让特定的人更容易理解。 (恕我直言,标签让人想起 BASIC/GOTO 时代,通常会产生 Spaghetti 代码) 。

额外加分:询问你的朋友是否曾经用 BASIC 编写;我敢打赌你会得到一个“是”(以及在课程期间的很多坏习惯——这不是要描述的,我只是从未在[当前的]之后与 BASIC/VB 程序员有过良好的经验。 ] 编码模式))

break 命令通常用于退出循环,但是如果代码块嵌套在标签内,则您将建立另一个可以中断的块。它还为您提供了更多的灵活性来决定中断从哪里退出。例如:

for (;;){ // "for a"
  for(;;){ // "for b"
    break; // breaks "for b"
  }
}

在本例中,break 仅意味着退出嵌套(“for b”)循环。但是:

myblock: {
  for(;;){
    for(;;){
      break mybock; // breaks label "myblock"
    }
  }
}

在这种情况下,break 实际上退出了两个循环,因为您指示它完全退出标签块。这几乎就像:

function myblock(){
  for(;;){
    for(;;){
      return; // exits function "myblock"
    }
  }
}

return 退出块的方式类似于 break myblock 的行为方式。


顺便说一句,并非没有原因,我发现这更容易阅读:

var again = true;
while (again){
    var num = (new Date()).getMilliseconds() % 100,
        guess = +prompt("I'm thinking of a number between 0 and 100. Try to guess it.", "1"),
        guesses = 1;
    while (num !== guess){
        guesses++;
        guess = +prompt((guess < num ? "Too low." : "Too high.") + " Try again.", guess);
    }
    alert("You got it in " + guesses + " guesses! The number is " + num);
    again = prompt("Do you want to guess again? (y/n)", "y") == "y";
}

Breaks can in fact have labels (and do so accept them). However, I'm not sure who "He" is, but I would go as far as to say "He" is conveying his ideals of programming, rather than a specific standard. That is to say, there's no need to use labels, it just makes it more legible to that particular person. (And, IMHO, labels are reminiscent of the BASIC/GOTO days which usually results in Spaghetti Code).

Extra Credit: Ask your friend if they used to write in BASIC; I'm betting you'll get a "yes" (along with a lot of bad habits for the duration of the course--that's not to profile, I've just never had a good experience with BASIC/VB programmers following [current] coding patterns))

The break command is commonly used to exit loops, however if the code block is nested within a label, you're establishing yet another block which you can break from. It also gives you a bit more flexibility as to where the break is meant to exit from. For example:

for (;;){ // "for a"
  for(;;){ // "for b"
    break; // breaks "for b"
  }
}

In this instance, break is only meant to exit the nested ("for b") loop. However:

myblock: {
  for(;;){
    for(;;){
      break mybock; // breaks label "myblock"
    }
  }
}

In this case, break is actually exiting both loops because you're instructing it to quit the label block entirely. This would be almost like having:

function myblock(){
  for(;;){
    for(;;){
      return; // exits function "myblock"
    }
  }
}

Where return exits the block similar to the way break myblock acts.


By the way, not for nothing, I find this a tad easier to read:

var again = true;
while (again){
    var num = (new Date()).getMilliseconds() % 100,
        guess = +prompt("I'm thinking of a number between 0 and 100. Try to guess it.", "1"),
        guesses = 1;
    while (num !== guess){
        guesses++;
        guess = +prompt((guess < num ? "Too low." : "Too high.") + " Try again.", guess);
    }
    alert("You got it in " + guesses + " guesses! The number is " + num);
    again = prompt("Do you want to guess again? (y/n)", "y") == "y";
}
人海汹涌 2025-01-10 09:18:15

经过对 label< 的一些研究,我可以理解代码/a> 和 break 在 JavaScript 中。然而,我个人不喜欢这种编码风格,主要是因为标记的 block 语法与文字对象表示法太相似 - 我经常使用它。甚至 Mozilla 的标签文档也告诉我们要避免使用它们:

标签在 JavaScript 中并不常用,因为它们使程序更难阅读和理解。尽可能避免使用标签,并且根据情况,更喜欢调用函数或抛出错误。

关于您的客观问题:

  1. break 可用于退出 for 循环、while 循环和 case 语句,以及标记的

  2. 不能使用break退出函数,必须使用return

I can understand the code after a little research on label and break in javascript. However, I personally don't like that style of coding, mainly because the labelled block syntax is too similar to the literal object notation - which I use a lot. And even Mozilla's documentation on labels tell us to avoid them:

Labels are not very commonly used in JavaScript since they make programs harder to read an understand. As much as possible, avoid using labels and, depending on the cases, prefer calling functions or throwing an error.

Regarding your objective questions:

  1. break can be used to exit for loops, while loops and case statements, as well as labelled blocks.

  2. You cannot use break to exit a function, you must use return.

陌上青苔 2025-01-10 09:18:15

来自 MDN (粗体强调是我的):

break 语句包含一个可选标签,允许程序
打破标签声明。 break 语句需要是
嵌套在这个带标签的语句中。 带标签的语句可以是
任何 block 语句;它前面不必有循环
声明。

因此,是的,标签可以在循环之外使用,但是,不,您不能使用它们从函数返回。

From MDN (bold emphasis mine):

The break statement includes an optional label that allows the program
to break out of a labeled statement. The break statement needs to be
nested within this labelled statement. The labelled statement can be
any block statement; it does not have to be preceded by a loop
statement.

So, yes, labels can be used outside of loops, but, no, you can't use them to return from a function.

超可爱的懒熊 2025-01-10 09:18:15

这些 break 语句的使用方式与旧语言中使用 goto 的方式相同。正如 Shark 指出的那样:您也可以在 switch 语句中使用它们,但不能在函数中使用它们。

这可能会让您感到困惑,因为他将标记块与无限 for(;;) 循环结合使用。

请参阅此处的这篇文章了解更多信息:http://james.padolsey.com/javascript /labelled-blocks-useful/

Those break statements are being used in the same way that goto is used in older languages. And as Shark pointed out: you can also use them in switch statements, but not in functions.

It's probably confusing to you because he is using the labeled blocks in conjunction with infinite for(;;) loops.

Look at this article here for more information: http://james.padolsey.com/javascript/labelled-blocks-useful/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文