Possible Duplicate:
How to use Math.max, etc. as higher-order functions
Using Mozilla's Javascript 1.6 array 'extension' functions (map, reduce, filter etc.), why is it that the following works as expected:
var max = [1,2,3].reduce(function(a,b) { return Math.max(a,b); });
But the following does not work (it produces NaN):
var max2 = [1,2,3].reduce(Math.max);
Is it because Math.max is a variadic function?
max() The Math. max() function returns the largest of the zero or more numbers given as input parameters, or NaN if any parameter isn't a number and can't be converted into one.
Get the max value in the array, using the Math. max() method. Call the indexOf() method on the array, passing it the max value. The indexOf method returns the index of the first occurrence of the value in the array or -1 if the value is not found.
The Math. max() method is used to return the largest of zero or more numbers. The result is “-Infinity” if no arguments are passed and the result is NaN if at least one of the arguments cannot be converted to a number. The max() is a static method of Math, therefore, it is always used as Math.
max is returning -Infinity when there is no argument passed. If no arguments are given, the result is -∞. So when you spread an empty array in a function call, it is like calling the function without an argument. But the result is negative infinity, not positive.
Math.max
does not know what to do with all the extra variables function(previousValue, currentValue, index, array)
mainly that array at the end.
[].reduce.call([1,2,3,6],function(a,b) { return Math.max(a,b); });
This works and uses .call
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