PDA

View Full Version : JS help with min/max variable values

Josh13
10-09-2011, 11:49 PM
Hello, I am new here, and I will probably break some of the forum rules on accident and I apologize ahead of time, but please go easy on me. I have a problem with a question in a Javascript class I am taking currently. The book explains how to detect the smallest values the user inputs but does not explain how to detect already declared variables that have values in them and how to detect which of these declared variables has the smallest number. For example:

double aA = 3.7;
double aB = 5.8;
double aC = 1.9;
double aMin; // this is the variable I want the program to detect and stick
// the smallest variable into.

I want the code to detect the variable containing the smallest number and it has to be able to detect negative numbers as well.

I am completely lost on how to do this! Any help would be appreciated!

Thank you!

jmrker
10-10-2011, 12:28 AM
That does not look like Javascript to me. 'double' is more likely Java.
Are you sure you are in the correct forum?

Javascript solution would look more like:

<script type="text/javascript">
var aA = 3.7;
var aB = 5.8;
var aC = 1.9;
var aMin = Infinity; // this is the variable I want the program to detect and stick the smallest variable into.

if (aA < aMin) { aMin = aA; }
if (aB < aMin) { aMin = aB; }
if (aC < aMin) { aMin = aC; }
</script>

There are easier ways to do this, especially if your variables are part of an array.

var aArray = [3.7,5.8,1.9,7.2];
var aMin = Infinity;
for (var i=0; i<aArray.length; ++i) { if (aArray[i] < aMin) { aMin = aArray[i]; } }