【问题标题】:Using the same code twice in JavaScript在 JavaScript 中两次使用相同的代码
【发布时间】:2015-07-09 12:36:40
【问题描述】:

我遇到了如下情况。 事情发生了,用户需要决定他是否要继续。 如果他不这样做,代码将停止执​​行。 如果他这样做,它将继续。

但是,我希望在顶部的 if 语句返回 false 时也执行该部分(大量代码),而不是两次使用相同的代码。

在 VB 中我会使用 GOTO,但在 Javascript 中没有等效项。

if(true){
    var r = confirm("although this and that... do you still want to continue?");
    if (r == false) {
        break;
    } else { 
        a lot of code
    }
}

有什么想法吗?

【问题讨论】:

  • 您在confirm 末尾缺少"
  • 你想在else中执行哪部分代码?JavaScript有return语句。
  • 能否请您详细说明..不太清楚您想要什么。

标签: javascript goto


【解决方案1】:

制作函数

function confirmPop(){
   if(true){
    var r = confirm("although this and that... do you still want to continue?");
    if (r == false) {
        break;
    } else { 
        a lot of code
    }
  }
}

然后打电话

confirmPop();

【讨论】:

  • 谢谢!这似乎是最明显的方式。
【解决方案2】:

如果我理解正确,你有这样的事情

if(booleanValue){
    var r = confirm("although this and that... do you still want to continue?");
    if (r == false) {
        break;
    } else { 
        a lot of code
    }
}else{
    a lot of code (the same as above)
}

在这种情况下,我会定义一个包含“大量代码”内容的函数,然后调用该函数两次。像这样

function doALotOfWork(){
    a lot of code
}
if(booleanValue){
    var r = confirm("although this and that... do you still want to continue?");
    if (r == false) {
        break;
    } else { 
        doALotOfWork();
    }
}else{
    doALotOfWork();
}

【讨论】:

    【解决方案3】:
    var r = confirm("although this and that... do you still want to continue?");
    // code to execute regardless of the option selected.
    if (r) {
        // code to execute only if the user wants to continue.
    } 
    

    【讨论】:

      【解决方案4】:

      将可重用逻辑包装到函数中,并将委托(调用的方法,例如“许多其他代码”)注入函数...

      var aLotOfCode = function () {
        // a lot of code here!
        console.log('a lot of code here!');
      };
      
      
      var confirmation = function (delegateIfRTrue)
      
        if(true){
          var r = confirm("although this and that... do you still want to continue?");
          if (r == false) {
              break;
          } else { 
              //a lot of code
              delegateIfRTrue();
          }
        }
      

      并使用...调用它

      confirmation(aLotOfCode);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-21
        • 2017-07-24
        • 2022-11-12
        • 1970-01-01
        • 2021-02-09
        • 2016-01-19
        • 2018-08-19
        • 1970-01-01
        相关资源
        最近更新 更多