【问题标题】:Breaking out of a while loop and switch in one go跳出while循环并一次性切换
【发布时间】:2015-01-28 21:49:12
【问题描述】:

在 C++ 中有一个关于这个问题的similar question,但我在这里使用的是 JavaScript。 我基本上和另一篇文章中的OP处于相同的情况。

var input = prompt();
while(true) {
    switch(input) {
        case 'hi':
        break;
        case 'bye':
            //I want to break out of the switch and the loop here
        break;
    }
    /*Other code*/
}

有没有办法做到这一点?

我在 /*Other code*/ 部分也有多个开关,代码也应该中断。

【问题讨论】:

    标签: javascript while-loop switch-statement break


    【解决方案1】:

    你可以在js中使用带有break语句的标签

    var input = prompt();
    
    outside:
    while(true) {
        switch(input) {
            case 'hi':
            break;
            case 'bye':
                //I want to break out of the switch and the loop here
            break outside;
        }
        /*Other code*/
    }
    

    【讨论】:

    • 是的,这是我接触的一种解决方案,但是当你有 10 个开关时标签开始失去可读性:)
    • 你确定你正在编写一个好的代码,因为你有 10 个开关? ;)
    • 你的意思是你有 10 个不同的退出点/循环,还是 switch 语句中有 10 个退出点打破了同一个循环。如果是后者,没有什么能阻止你多次使用同一个标签。
    • @Shomz 这是一款基于文本的游戏。我可能夸大了我拥有的开关数量:)
    【解决方案2】:

    将整个东西包装在一个函数中,然后您可以简单地return 打破两者。

    var input = prompt();
    (function () {
        while(true) {
            switch(input) {
                case 'hi':
                break;
                case 'bye':
                return;
            }
            /*Other code*/
        }
    })();
    

    【讨论】:

      【解决方案3】:

      这与 C++ 或大多数其他语言中的答案相同。基本上,你只需添加一个标志来告诉你的循环它已经完成了。

      var input = prompt();
      var keepGoing = true;
      while(keepGoing) {
          switch(input) {
              case 'hi':
                  break;
              case 'bye':
                  //I want to break out of the switch and the loop here
                  keepGoing = false;
                  break;
          }
          // If you need to skip other code, then use this:
          if (!keepGoing)  break;
          /*Other code*/
      }
      

      有意义吗?

      【讨论】:

      • 我已经在我的原始代码中尝试过这个,但是while 循环只在它内部的所有东西都运行之后才检查参数,这使得它对于停止执行中几乎没有用。
      • 这就是为什么你在它之后的其余代码之前有额外的检查。见上文。
      • 当然功能选项也不错,很JS。
      【解决方案4】:

      不要以“少一行代码”的名义降低可读性。明确你的意图:

      while (true) {
        var quit = false;
      
        switch(input) {
          case 'hi':
            break;
      
          case 'bye':
            quit = true;
            break;
        }
      
        if (quit)
          break;
      
        /*Other code*/
      }
      

      【讨论】:

      • Thought 的解决方案同样如此:我有多个开关,因此重复 if 语句来检查值是不切实际的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-25
      • 2020-08-13
      • 1970-01-01
      • 2021-08-31
      • 2016-01-18
      • 1970-01-01
      • 2023-04-09
      相关资源
      最近更新 更多