0

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

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 1do thing 2带有很多参数的函数调用,不知何故,似乎有不必要的重复。

有没有更好的方法来做到这一点?

4

2 回答 2

2
if (condition1 && (condition0 || !condition2)) {
  do thing 1
} else if (condition2) {
  do thing 2
}
于 2013-04-27T12:02:13.287 回答
1

为避免代码重复,您可以将做事 1 和做事 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();
    }
}
于 2013-04-27T11:58:54.360 回答