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

10-10-2011, 12:49 AM
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 aD = 7.2;
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!

10-10-2011, 01: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 aD = 7.2;
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; }
if (aD < aMin) { aMin = aD; }
alert('Smallest value is: '+aMin);

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]; } }
alert('Smallest value is: '+aMin);

10-10-2011, 01:40 AM
Thank you so much; I'm a complete noob and didn't know there was a difference between Java and Javascript. Yeah I am doing Java.. /facepalm. By the way your code worked with a few things changed around for Java. Thank you again! Sorry for the trouble.