Skip to content Skip to sidebar Skip to footer

How To Check If A Variable Is Larger Than Multiple Other Variables?

I need to check if a variable is greater than 4 other variables. Is there a way to do this? so far i've tried if(Guitar > Percussion || Brass || Keyboard || Woodwind)

Solution 1:

Guitar > Percussion || Brass || Keyboard || Woodwind

evaluates as

(Guitar > Percussion) || Brass || Keyboard || Woodwind

which will be true if Guitar > Percussion, or the first falsy value among Brass, Keyboard and Percussion.

What you want is (Guitar > Percussion && Guitar > Brass && Guitar > Keyboard && Guitar > Woodwind). Even better, you can do this:

var vals = [Guitar, Percussion, Brass, Keyboard, Woodwind];
var pageNames = ["GuitarPage", "PercussionPage", "BrassPage", "KeyboardPage", "WoodwindPage"];
var max = Math.max.apply(null, vals);
var index = vals.indexOf(max);
if (vals.indexOf(max, index + 1) == -1) {
  var pageName = pageNames[index];
  var page = document.getElementById(pageName);
  page.style.display = "block";
}

EDIT: The if checks if there is a second value that is also max, and avoids doing the operation in that case; this makes it equivalent to OP's code.

Solution 2:

For checking if a variable is greater than all other variable you need to use && instead of || as given below:

if (Percussion > Guitar && 
   Percussion > Brass && 
   Percussion > Keyboard && Percussion > Woodwind)

Solution 3:

Sadly, you must do it the long way, like so, for each of the variables:

if (Percussion > Guitar && Percussion > Brass && Percussion > Keyboard && Percussion > Woodwind)

This would check if the Percussion variable is greater than all of the other variables. Also, to check if the Percussion is greater than all of the other variables you must use && instead of ||, like in the example.

Good luck!

Post a Comment for "How To Check If A Variable Is Larger Than Multiple Other Variables?"