What condition is false in a multiple conditions if statement

空扰寡人 提交于 2019-12-06 03:46:14

Since the conditions are mutually exclusive, you can just use an else if without nesting.

if (condition1 && condition2 && condition3) {
    doSomething();
} else if (!condition1) {
    doWhatIDoWhenC1isFalse();
}
// add more else-if conditions as needed

If only one of your conditions can be false at a time (or if you don't care when two of them are false) then you can just have three else-if clauses and check each condition individually. If you do need to treat the cases where two conditions are false separately, you'll need an else-if for each combination. Pay close attention to the order you list them in if that's the case. The cases where you check if two conditions are both false should come before the cases where you only check one condition.

if (condition1 && condition2 && condition3) {
  doSomething();
}else if (!condition1){
  doWhatIDoWhenC1isFalse();
}else if (!condition2){
  doWhatIDoWhenC2isFalse();
}else{
  doWhatIDoWhenC3isFalse();
}

You have to do something along the lines of this. No way to cleanly get which expression that failed.

You may go this way if you want if any one of the condition is false:

if ((!condition1 && condition2 && condition3)||
   (condition1 && !condition2 && condition3)||
   (condition1 && condition2 && !condition3)) 
{
   doSomethingElse();      
} else {
  doSomething();
};

It can be:

var x = []; /* an array that will take expressions number that result true */

if(condition1) x.push(1);
if(condition2) x.push(2);
if(condition3) x.push(3);


if( x.length == 2 ){ /* if two conditions got true */
    doThingForTwoTrue();
}
if( x.length == 3 ){ /* if three conditions got true */
    doThingForThreeTrue();
}
if( x.indexOf(1) !== -1 ){ /* if condition1 got true */
    doThingOne();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!