如何使用 Math.max 等作为高阶函数 [英] How to use Math.max, etc. as higher-order functions
本文介绍了如何使用 Math.max 等作为高阶函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
简而言之,这是有效的:
In short, this works:
[1, 2, 3].reduce(function (a, b) { return Math.max(a, b); });
=> 3
但这不会:
[1, 2, 3].reduce(Math.max);
=> NaN
纯粹的困惑.
这是在 Firefox 3.5.9 中,我认为它使用的是 reduce、FWIW 的 mozilla 标准实现.
This is in Firefox 3.5.9, which I presume is using the mozilla standard implementation of reduce, FWIW.
推荐答案
Math.max
可以用作高阶函数.问题是 .reduce
将调用带有 4 个参数的函数:
Math.max
can be used as a higher-order function. The problem is .reduce
will call the function with 4 arguments:
Math.max(accumulator, value, index, the_array)
这里的 the_array
是一个数组,所以 Math.max
返回 NaN.我认为没有更简单的方法可以丢弃最后 2 个参数.
here is the_array
is an array, so Math.max
returns NaN. I don't think there's simpler way to discard the last 2 arguments.
这篇关于如何使用 Math.max 等作为高阶函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文