Click to See Complete Forum and Search --> : Max value of array with unknown Array length


hyperstyle
10-31-2003, 12:39 AM
I can't seem to find a way to get the maximum value of an array with an unknown quantity of variables in it. generally you'd write something like this:

tempmax=Math.max(ptotal[0],ptotal[1],ptotal[2],ptotal[3])

but that array 'ptotal' can range from having an array length of 1 to 6.

Is anyone able to help me out here. thanks

Gollum
10-31-2003, 03:11 AM
You might consider implementing your own max() function that takes an array as an argument, uses the .length property and inspects each element looking for the max.

Charles
10-31-2003, 04:58 AM
<script type="text/javascript">
<!--
Array.prototype.max = function () {
if (this.length == 0) return undefined;
var n = Number(this[0]);
for (var i=1; i<this.length; i++) {n = Math.max(n, this[i])};
return n;
}

alert ([1, 2, 3, 2, 1].max())
// -->
</script>

Khalid Ali
10-31-2003, 07:42 AM
Did I miss something here???
how come you are not able to use
array.length???

either its too early for me.:D. or yoru question does not make any sense

hyperstyle
11-01-2003, 07:00 AM
thanks charles, i didn't think to do it that way