Javascript 有条件地更改if-else块的顺序

Javascript 有条件地更改if-else块的顺序,javascript,if-statement,Javascript,If Statement,有没有一个优雅的方法来解决这个问题 if (condition0) { if(condition1) { do thing 1 } else if(condition2){ do thing 2 } } else { if(condition2) { do thing 2 } else if(condition1){ do thing 1 } } do thing 1和do thing 2函数调用包含大量参数,而且似乎存在不必要的

有没有一个优雅的方法来解决这个问题

if (condition0) {
  if(condition1) {
    do thing 1
  }
  else if(condition2){
    do thing 2
  }
}
else {
  if(condition2) {
    do thing 2
  }
  else if(condition1){
    do thing 1
  }
}
do thing 1
do thing 2
函数调用包含大量参数,而且似乎存在不必要的重复


有更好的方法吗?

为了避免代码重复,可以在函数中存储do thing 1和do thing 2。把它弄干净

var DoThing1 = function ()
{
   do thing 1
}

var DoThing2 = function ()
{
    do thing 2
}
if (condition0) {
    if(condition1) {
        DoThing1();
    }
    else if(condition2){
        DoThing2();
    }
}
else {
    if(condition2) {
        DoThing2(); 
    }
    else if(condition1){
        DoThing1();
    }
}

为了避免代码重复,可以在函数中存储do Thing1和do Thing2。把它弄干净

var DoThing1 = function ()
{
   do thing 1
}

var DoThing2 = function ()
{
    do thing 2
}
if (condition0) {
    if(condition1) {
        DoThing1();
    }
    else if(condition2){
        DoThing2();
    }
}
else {
    if(condition2) {
        DoThing2(); 
    }
    else if(condition1){
        DoThing1();
    }
}

谢谢在这个行业,如果我这样做,人们会喜欢它吗?还是正常的方式?我想这取决于条件的复杂程度与“做事”的复杂性。一般来说,您会尽量避免冗余:人们可能会在“do thing 1”中发现错误,然后忘记更新第二次呼叫…如果情况复杂且没有副作用,考虑将它们一起测试,并将它们存储在非常好的布尔变量中,这将使斯特凡的代码读起来比长条件检查要容易得多——这是最短的可能形式。1@tucuxi:这对一些人(包括我)会有帮助,但是这可能会浪费变量,在代码中可能会被视为“噪音”。谢谢。在这个行业,如果我这样做,人们会喜欢它吗?还是正常的方式?我想这取决于条件的复杂程度与“做事”的复杂性。一般来说,您会尽量避免冗余:人们可能会在“do thing 1”中发现错误,然后忘记更新第二次呼叫…如果情况复杂且没有副作用,考虑将它们一起测试,并将它们存储在非常好的布尔变量中,这将使斯特凡的代码读起来比长条件检查要容易得多——这是最短的可能形式。1@tucuxi:这对一些人(包括我)是有帮助的,但是这可能是对变量的浪费,在代码中可能被认为是“噪音”。