开发者

How to use Math.max, etc. as higher-order functions

开发者 https://www.devze.com 2022-12-30 22:18 出处:网络
In short, this works: [1, 2, 3].reduce(function (a, b) { return Math.max(a, b); }); => 3 But this doesn\'t:开发者_如何学C

In short, this works:

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

But this doesn't:开发者_如何学C

[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.apply(Math, [1, 2, 3]);
//3


Not exactly a higher order use, but this also works:

Math.max(...myArray);
0

精彩评论

暂无评论...
验证码 换一张
取 消