How might I find the largest number contained in a JavaScript array?
You can use the apply function, to call Math.max:
var array = [267, 306, 108];
var largest = Math.max.apply(Math, array); // 306
How does it work?
The apply function is used to call another function, with a given context and arguments, provided as an array. The min and max functions can take an arbitrary number of input arguments: Math.max(val1, val2, ..., valN)
So if we call:
Math.min.apply(Math, [1, 2, 3, 4]);
The apply function will execute:
Math.min(1, 2, 3, 4);
Note that the first parameter, the context, is not important for these functions since they are static. They will work regardless of what is passed as the context.
Resig to the rescue:
Array.max = function( array ){
return Math.max.apply( Math, array );
};
Warning: since the maximum number of arguments is as low as 65535 on some VMs, use a for loop if you're not certain the array is that small.