【发布时间】:2011-12-07 17:45:23
【问题描述】:
我正在尝试一项显而易见的任务:
var maxVal = [ 1, 2, 3, 4, 5 ].reduce( Math.max, 0 );
然后得到:
NaN
结果。为了使它工作,我必须以这种方式创建一个匿名函数:
var maxVal = [ 1, 2, 3, 4, 5 ].reduce( function ( a, b ) {
return Math.max(a, b);
}, 0 );
谁能告诉我为什么?两者都是接受两个参数并且都返回一个值的函数。有什么区别?
另一个例子可能是这样的:
var newList = [[1, 2, 3], [4, 5, 6]].reduce( Array.concat, [] );
结果是:
[1, 2, 3, 0, #1=[1, 2, 3], #2=[4, 5, 6], 4, 5, 6, 1, #1#, #2#]
我只能在这个形状下在 node.js 中运行这个例子(在我现在使用的 node.js v4.12 中数组没有 concat):
var newList = [[1, 2, 3], [4, 5, 6]].reduce( [].concat, [] );
然后得到这个:
[ {}, {}, 1, 2, 3, 0, [ 1, 2, 3 ], [ 4, 5, 6 ], 4, 5, 6, 1, [ 1, 2, 3 ], [ 4, 5, 6 ] ]
为什么会这样?
【问题讨论】:
标签: javascript node.js reduce higher-order-functions