This is what I tried:
Math.min([1,2,3])
But only get NaN
...
use apply
:
Math.min.apply(null,[1,2,3]); //=> 1
From devguru:
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]);
Use JS spread operator to avoid extra coding:
console.log(Math.min(...[1,2,3]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With