2013-04-27 95 views
0

有没有一种优雅的方法来解决这个问题?有条件地改变if-else块的顺序

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功能有很多的参数调用,并不知它好像有不必要的重复。

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

回答

2
if (condition1 && (condition0 || !condition2)) { 
    do thing 1 
} else if (condition2) { 
    do thing 2 
} 
+0

感谢。在这个行业中,如果我这样做,或者正常的方式,人们会喜欢吗? – batman 2013-04-27 12:05:01

+0

我想这取决于条件的复杂程度与“做事情”的复杂程度。一般情况下,您尽量避免冗余:人们可能会在“做事1”时发现错误,然后忘记更新第二个电话...... – 2013-04-27 12:07:36

+1

如果条件复杂且没有副作用,请考虑一起测试它们并将它们存储在非常有名的布尔变量中 - 这将使Stefan的代码比长条件更容易阅读 – tucuxi 2013-04-27 12:11:29

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