This is what I tried:
Math.min([1,2,3])
But only get NaN...
use apply:
Math.min.apply(null,[1,2,3]); //=> 1
Function.apply(thisArg[, argArray])the apply method allows you to call a function and specify what the keyword this will refer to within the context of that function. The thisArg argument should be an object. Within the context of the function being called, this will refer to thisArg. The second argument to the apply method is an array. The elements of this array will be passed as the arguments to the function being called. The argArray parameter can be either an array literal or the deprecated arguments property of a function.
In this case the first argument is of no importance (hence: null), the second is, because the array is passed as arguments to Math.min. So that's the 'trick' used here.
[edit nov. 2020] This answer is rather old. Nowadays (with Es20xx) you can use the spread syntax to spread an array to arguments for Math.min.
Math.min(...[1,2,3]);
Math.min(1, 2, 3)
1
Since, [1,2,3] cannot be converted to a number, it returns NaN.
More: Mozilla Reference
Use this
Array.min = function( array ){
return Math.min.apply( Math, array );
};
Check this link out - http://ejohn.org/blog/fast-javascript-maxmin/
Don't pass it an array (which is what is not a number or NaN in this case), just pass it the numbers as arguments to the function. Like this:
Math.min(1, 2, 3)
Math.min() which takes an array and breaks it up before calling Math.min() with the array's elements. (And even checks the input to make sure they're all numbers.)