为什么我不能在Javascript中编写[1,2,3] .reduce(Math.max)?

sac*_*eie 13 javascript functional-programming

可能重复:
如何使用Math.max等作为高阶函数

使用Mozilla的Javascript 1.6数组'扩展'函数(map,reduce,filter等),为什么以下按预期工作:

var max = [1,2,3].reduce(function(a,b) { return Math.max(a,b); });
Run Code Online (Sandbox Code Playgroud)

但以下不起作用(它产生NaN):

var max2 = [1,2,3].reduce(Math.max);
Run Code Online (Sandbox Code Playgroud)

是因为Math.max是一个可变函数吗?

Joe*_*Joe 15

Math.max不知道如何处理所有额外的变量,function(previousValue, currentValue, index, array)主要是最后的数组.

[].reduce.call([1,2,3,6],function(a,b) { return Math.max(a,b); });
Run Code Online (Sandbox Code Playgroud)

这工作并使用.call

  • 如果要将数组作为`this`值传递,为什么要使用.call()?这只是一个过于复杂的方式来做OP已经在问题中显示的内容. (4认同)