PDA

View Full Version : do something based on match in if statement



Snookerman
03-24-2010, 09:45 AM
I have an if statement with three possible matches and depending on those matches, I want to do something. The code looks like this:

if (result1 == result2 & result2 == result3){
points = result1 + result2 + result3;
} else if (result1 == result2 || result1 == result3 || result2 == result3){
//points should equal the sum of the match
}
If all three results are a match, the points should be the sum of them, however, if only two are a match, only the sum of those two should be the points. I know I could just use three if statements for the last part, but I'm just curious if it's possible to just use one.

jscheuer1
03-24-2010, 05:48 PM
As far as I can tell, you would have to have three if statements to replace:



//points should equal the sum of the match

anyway, so may as well do without:



else if (result1 == result2 || result1 == result3 || result2 == result3)

and have a total of four, instead of a total of five as would be required doing it the way you are trying.

This might work, but using if/if else statements seems clearer, and could more easily be expanded to include more results:


if (result1 == result2 & result2 == result3){
points = result1 * 3;
} else {
var results = [result1, result2, result3];
for(var i = 0; i < results.length; ++i){
for (var j = results.length - 1; j > -1; --j){
if(i !== j && results[i] == results[j]){
points = 2 * results[i];
}
}
}
}

Snookerman
03-25-2010, 06:51 PM
Thanks John, I ended up using the first one. The second one is a bit too complicated for me right now, but hopefully I'll get it in a few weeks. (I'm taking Javascript :D)