JavaScript reduce 无法处理数学函数?
我正在尝试一项显而易见的任务:
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 ] ]
为什么是那?
I'm trying an obvious task:
var maxVal = [ 1, 2, 3, 4, 5 ].reduce( Math.max, 0 );
and get:
NaN
as the result. To make it work I have to make an anonymous function this way:
var maxVal = [ 1, 2, 3, 4, 5 ].reduce( function ( a, b ) {
return Math.max(a, b);
}, 0 );
Could someone tell me why? Both are functions that take two arguments and both return one value. What's the difference?
Another example could be this:
var newList = [[1, 2, 3], [4, 5, 6]].reduce( Array.concat, [] );
The result is:
[1, 2, 3, 0, #1=[1, 2, 3], #2=[4, 5, 6], 4, 5, 6, 1, #1#, #2#]
I can run this example in node.js only under this shape (Array has no concat in node.js v4.12, which I use now):
var newList = [[1, 2, 3], [4, 5, 6]].reduce( [].concat, [] );
and then get this:
[ {}, {}, 1, 2, 3, 0, [ 1, 2, 3 ], [ 4, 5, 6 ], 4, 5, 6, 1, [ 1, 2, 3 ], [ 4, 5, 6 ] ]
And why is that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
传递给
reduce
的函数需要超过2 个参数:previousValue
currentValue
index
array
Math.max
将评估全部参数并返回最高值:因此,如果将
Math.max
传递给reduce
,它将返回所传递的 4 个参数中的最高值,其中一个是数组。传递数组将使Math.max
返回NaN
,因为数组不是数字。这是规范 (15.8.2.11) 中的内容:ToNumber
将为数组返回NaN
。因此,使用
Math.max
进行归约最终将返回NaN
。The function passed to
reduce
takes more than 2 arguments:previousValue
currentValue
index
array
Math.max
will evaluate all arguments and return the highest:So in case of passing
Math.max
toreduce
, it will return the highest value from the 4 arguments passed, of which one is an array. Passing an array will makeMath.max
returnNaN
because an array is not a number. This is in the specs (15.8.2.11):ToNumber
will returnNaN
for an array.So reducing with
Math.max
will returnNaN
in the end.由于 Math.max 接受多个参数,因此您只需通过 apply 函数将数组转换为参数列表即可。
请参阅此处的警告了解此技术的局限性。
Since
Math.max
accepts multiple arguments, you can just convert the array to a parameter list via theapply
function.See warnings here on limitations of this technique.
将数组减少到最大值的另一种方法:(
说明了减少的工作原理,但并不是说这是从数组中获取最大数的最佳方法)
Another way to reduce an array to its max value:
(illustrating how reduce works, not that it is the best way to get the max number from an array)