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

时间:2015-07-09 12:36:41

标签: javascript goto

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

然而,我不是两次使用相同的代码,而是在顶部的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
    }
}

有什么想法吗?

4 个答案:

答案 0 :(得分: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();

答案 1 :(得分:1)

如果我理解正确你有类似的东西

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

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