【问题标题】:Return to previous level with early return提前返回到之前的水平
【发布时间】:2020-10-14 02:54:00
【问题描述】:

function myFunc() {
  if (1 == 1) {
    console.log('1 == 1')
    if (2 == 2) return
    console.log('2 !== 2')
    ///other code
  }
  if (3 == 3) {
    console.log('3 == 3')
  }
}
myFunc()

对于这个函数,我想说的是“如果2 == 2,你可以提前退出当前的if块并返回到上一级。然后继续执行下一个块(if (3 == 3){...})。”但是return函数直接退出了整个函数。有没有办法做到这一点?

【问题讨论】:

  • 1==1 将始终返回 true。您尝试执行的分支类型类似于使用 goto 和 label:,我强烈建议您不要这样做。行为和程序流程对于任何有点复杂的事情都很难推理。
  • 这就是return 的定义,它从函数中返回。没有什么可以从if 级别退出。
  • @TalmacelMarianSilviu break 仅用于循环,不适用于 if
  • if (2 !== 2) { /* other code */ }怎么样
  • @user120242 更不用说 JavaScript 没有 goto

标签: javascript if-statement return


【解决方案1】:

您可以使用 IIFE。 return 将从 IIFE 返回,而不是包含函数:

function myFunc() {
  if (1 == 1) {
    console.log('1 == 1');
    (function() {
      if (2 == 2) return;
      console.log('2 !== 2')
    })();
  }
  if (3 == 3) {
    console.log('3 == 3');
  }
}
myFunc();

【讨论】:

    【解决方案2】:

    另一种方法是首先不输入第一个 if 条件。如果你想运行代码 if 1==1 除非 2==2 我会使用:

    function myFunc() {
      if (1 == 1 && 2!==2) {
        console.log('1 == 1')
    
        ///other code
      }
      if (3 == 3) {
        console.log('3 == 3')
      }
    }
    myFunc()
    

    【讨论】:

      【解决方案3】:

      正如@user120242 所说,1==1 始终为真,使用 goto 和 label 效率不高,根本不推荐。

      对于您的问题,您可以使用多种功能。每个函数都会检查一些东西 这可能是解决它的一种方法:

      function myFunc() {
       if (1 == 1) {
        console.log("1==1");
        if( 2 == 2 ) { // can also get an own function
         callNextFunc(); // contains the 3==3 function
         return;
        }
        else {
         console.log("2!=2");
         // other code
         callNextFunc();
        }
       }
      }
      

      使用函数可以让您轻松返回和跳过部分代码。

      【讨论】:

        【解决方案4】:

        虽然有点 hacky!!,你也许可以使用 switch,case..

        例如..

        function myFunc() {
          switch (1) {
            case 1: {
              console.log('1 == 1')
              if (2 === 2) break;
              console.log('2 !== 2')
            }
          }
          if (3 == 3) {
            console.log('3 == 3')
          }
        }
        myFunc()

        【讨论】:

          【解决方案5】:

          要么按照我在评论中的建议使用switch,然后由某人在他们的回答中使用,要么修改代码,将return替换为;,并将其余部分用{}包装,前面加上@987654325 @...

          并使用分号!!!

          function myFunc() {
            if (1 == 1) {
              console.log('1 == 1');
              if (2 == 2) ;
              else {
                console.log('2 !== 2');
                ///other code
              }
            }
            if (3 == 3) {
              console.log('3 == 3');
            }
          };
          myFunc();

          【讨论】:

            猜你喜欢
            • 2013-02-13
            • 2012-08-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-04-14
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多