JavaScript Map Reduce:奇怪的行为

AsT*_*TeR 3 javascript mapreduce

var t = [-12, 57, 22, 12, -120, -3];

t.map(Math.abs).reduce(function(current, previousResult) {
    return Math.min(current, previousResult);
}); // returns 3

t.map(Math.abs).reduce(Math.min); // returns NaN
Run Code Online (Sandbox Code Playgroud)

我不明白为什么第二种形式不起作用.欢迎任何解释.

编辑:技术背景:Chrome和Firefox JavaScript引擎.见ES5减少http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.21

Ben*_*aum 6

Math.min接受多个参数.这与其不适用于此类功能的原因完全相同parseInt.你需要自己绑定参数.

降低饲料类的价值观indexarrayMath.min

如果我们按照以下步骤,我们可以确认这一点:

首先,我们代理Math.min:

var oldMath = Math.min;
Math.min = function (){
   console.log(arguments)
   return oldMath.apply(Math, arguments);
}
Run Code Online (Sandbox Code Playgroud)

然后我们运行第二个版本:

[-12, 57, 22, 12, -120, -3].reduce(Math.min);
Run Code Online (Sandbox Code Playgroud)

哪些日志:

[-12, 57, 1, Array[6]]
Run Code Online (Sandbox Code Playgroud)

由于Array [6]不是数字,因此结果为NaN


以下是来自MDN的非常类似的示例:

["1", "2", "3"].map(parseInt);
Run Code Online (Sandbox Code Playgroud)

虽然人们可以期待[1,2,3]但实际结果是[1,NaN,NaN]

parseInt通常与一个参数一起使用,但需要两个参数.第二个是基数对于回调函数,Array.prototype.map传递3个参数:元素,索引,数组第三个参数被parseInt忽略,但不是第二个参数,因此可能会产生混淆.