最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked May 18, 2010 at 11:21 cemerickcemerick 5,9165 gold badges32 silver badges52 bronze badges 4
  • Terminology nitpick: You're not trying to use Math.max as a higher-order function, but to use it as an argument to a higher-order function. Using it as a higher order function would mean to use it with arguments that are functions (or to use it so that it returns a function). – sepp2k Commented May 18, 2010 at 11:50
  • @sepp2k Perfectly fair nitpick. :-) – cemerick Commented May 18, 2010 at 13:35
  • Reduce spec is here developer.mozilla.org/en-US/docs/JavaScript/Reference/… – Petr Gladkikh Commented Sep 27, 2012 at 7:45
  • That's a little disappointing. In Scheme, one of the main sources of inspiration for JavaScript, you can even use operators like + or * as arguments to "reduce," e.g. (reduce + '(1 2 3 4 5)) – Ron Inbar Commented Oct 20, 2017 at 16:36
Add a comment  | 

3 Answers 3

Reset to default 22

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)

  1. 暂无评论