Why doesn't using Math.max as a parameter work in this scenario?

I answered a question related to Array.reduce using Math.max in my example, and I found what I don't understand:

It works:

let values=[4,5,6,77,8,12,0,9];

let max=values.reduce((acc,curr) => Math.max(acc,curr),0);

console.log(max);
Run codeHide result

But if I try something like this:

let values=[4,5,6,77,8,12,0,9];

let max=values.reduce(Math.max,0);

console.log(max);
Run codeHide result

It returns NaN.

I thought the context was the reason, so I wrote the following:

let max=Math.max;
console.log(max(2,5));
Run codeHide result

But it worked as expected!

What am I missing? MDN says that:

If at least one of the arguments cannot be converted to a number, NaN is returned.

+4
source share
1 answer

, , reduce , . 4.

. : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Description

:

accumulator
currentValue
currentIndex
array (a reference to the array itself)

- , , reduce. Math.max , NaN.

EDIT: apply !

let values = [4,5,6,77,8,12,0,9];
let max = Math.max.apply(null, values);
let maxAnotherWay = Math.max(...values);

, Lodash, _.ary , :

let values = [4,5,6,77,8,12,0,9];
let max = values.reduce(_.ary(Math.max, 2),0);
+4

Source: https://habr.com/ru/post/1684620/


All Articles