Calling Array.reduce on an array with a single element in Javascript

Calling reduce on an empty array throws TypeError which is perfectly understandable and helps catching bugs. But when I call it on an array with a single item inside, the behavior confuses me:

var arr = ["a"];
arr.reduce(function(a,b){
   return [a,b]
}); //returns "a"

I know that reduce is not meant to be used on such an array, but I find that returning just the element without invoking the callback or throwing an error is at least strange.

Furthermore, the MDN documentation states that the callback is a "Function to execute on each value in the array, taking four arguments:".

Can someone explain the reasoning behind this behaviour?


The callback is supposed to be a "binary function" (ie one that takes two arguments to operate on, plus the additional two arguments that hold the currentIndex and the original array ).

If only one element is supplied, you would be passing an undefined value to the callback for either currentValue or previousValue , potentially causing runtime errors.

The design therefore assumes that given only one value (whether that be an empty array, and an initialValue , or an array with one value and no initialValue ) it's better not to invoke the callback at all.

链接地址: http://www.djcxy.com/p/74154.html

上一篇: 在关闭浏览器之前Javascript警告不按预期工作

下一篇: 在使用Javascript中的单个元素的数组上调用Array.reduce