为什么使用Math.max作为参数在这种情况下不起作用?

时间:2017-08-28 16:18:56

标签: javascript lambda

我在我的例子中使用Math.max回答了question related to Array.reduce,我发现了一些我不明白的事情:

这有效:



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

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

console.log(max);




但如果我尝试这样的事情:



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

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

console.log(max);




它返回NaN。

我认为背景是原因,所以我写了以下内容:



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




但它按预期工作了!

我错过了什么? MDN says那个:

  

如果至少有一个参数无法转换为数字,则为NaN   归还。

1 个答案:

答案 0 :(得分:4)

您缺少的是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

编辑:相反,您可以使用apply方法或新的点差运算符!

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

OR ,如果你碰巧使用Lodash,_.ary方法允许你将函数包装在另一个限制其 arity 的函数中:

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