问题
I'm writing a multiple if statement in Javascript. I've 3 (or more) conditions, and I wanna doSomething() only if all these 3 conditions are true. If only one of these 3 are false, I wanna doSomethingElse(). I think my code it's right, but my problem is on another level. What if I wanna know for which condition my statement is false? E.g.: condition1=true, condition2=true, condition3=false.
if (condition1 && condition2 && condition3) {
doSomething();
} else {
doSomethingElse();
};
I've thought that I can put another if statement in the else part.
if (condition1 && condition2 && condition3) {
doSomething();
} else {
if (condition1 == false) {
doWhatIDoWhenC1isFalse();
};
};
Is this the right way? Is there any other way to do this? Maybe faster way! Thank for your help, and be nice to me, it's my second day on Javascript :)
回答1:
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.
回答2:
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.
回答3:
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();
};
回答4:
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();
}
来源:https://stackoverflow.com/questions/27968511/what-condition-is-false-in-a-multiple-conditions-if-statement