JavaScript reduce无法处理数学函数? [英] JavaScript reduce can't handle Math functions?

查看:107
本文介绍了JavaScript reduce无法处理数学函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试一项明显的任务:

I'm trying an obvious task:

var maxVal = [ 1, 2, 3, 4, 5 ].reduce( Math.max, 0 );

并获取:

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?

另一个例子可能是:

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,我现在使用):

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, [] );    

然后得到:

[ {}, {}, 1, 2, 3, 0, [ 1, 2, 3 ], [ 4, 5, 6 ], 4, 5, 6, 1, [ 1, 2, 3 ], [ 4, 5, 6 ] ]

为什么会这样?

推荐答案

传递给的函数减少 需要2个以上的参数


  • previousValue

  • currentValue

  • index

  • array

  • previousValue
  • currentValue
  • index
  • array

Math.max 将评估所有参数并返回最高:

Math.max will evaluate all arguments and return the highest:

Math.max(1, 2, 3, 4) === 4;

因此,如果传递 Math.max reduce ,它将返回传递的4个参数中的最高值,其中一个是数组。传递数组将使 Math.max 返回 NaN ,因为数组不是数字。这是在规范(15.8.2.11)中:

So in case of passing Math.max to reduce, it will return the highest value from the 4 arguments passed, of which one is an array. Passing an array will make Math.max return NaN because an array is not a number. This is in the specs (15.8.2.11):


给定零个或多个参数,在每个参数上调用ToNumber并返回最大值结果值。

Given zero or more arguments, calls ToNumber on each of the arguments and returns the largest of the resulting values.

...

如果任何值为NaN,则结果为NaN

If any value is NaN, the result is NaN

ToNumber 将返回 NaN 对于数组。

因此,使用 Math.max 减少将返回 NaN 最后。

So reducing with Math.max will return NaN in the end.

这篇关于JavaScript reduce无法处理数学函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆