如何使用Math.max等作为高阶函数 [英] How to use Math.max, etc. as higher-order functions

查看:119
本文介绍了如何使用Math.max等作为高阶函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之,这是有效的:

  [1,2,3] .reduce(function(a,b){返回Math.max(a,b);}); 
=> 3

但这并不是:

  [1,2,3] .reduce(Math.max); 
=> NaN

纯粹困惑。

在Firefox 3.5.9,这我相信是使用 Mozilla的标准执行降低,FWIW。

解决方案

Math.max 可以用作高阶函数。问题是 .reduce 会用4个参数调用函数:

  Math.max(accumulator,value,index,the_array)

这里是 the_array 是一个数组,所以 Math.max 返回NaN。我不认为有放弃最后2个参数的简单方法。


In short, this works:

[1, 2, 3].reduce(function (a, b) { return Math.max(a, b); });
=> 3

But this doesn't:

[1, 2, 3].reduce(Math.max);
=> NaN

Pure puzzlement.

This is in Firefox 3.5.9, which I presume is using the mozilla standard implementation of reduce, FWIW.

解决方案

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)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆