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

前端 未结 2 753
醉梦人生
醉梦人生 2020-12-03 14:38

In short, this works:

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

But this doesn\'t:

[1, 2, 3].re         


        
相关标签:
2条回答
  • 2020-12-03 14:57

    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.

    0 讨论(0)
  • 2020-12-03 15:08
    Math.max.apply(Math, [1, 2, 3]);
    //3
    
    0 讨论(0)
提交回复
热议问题