我在我的例子中使用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 归还。
答案 0 :(得分:4)
您缺少的是reduce
的回调更多参数而不仅仅是累加器和当前数组值。它实际上有4个。
四个参数:
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);