在 JavaScript 中两次使用相同的代码

Using the same code twice in JavaScript

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

然而,与其使用相同的代码两次,我希望当顶部的 if 语句 returns 为 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
    }
}

有什么想法吗?

创建函数

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();
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.
} 

如果我没理解错的话你有这样的东西

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)
}

在那种情况下,我会用 "a lot of code" 的内容定义一个函数,然后调用该函数两次。像这样

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();
}

将可重用的逻辑包装到函数中,并将委托(调用方法,例如"a lot of other code")注入到函数中...

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);