在Javascript中使用单个元素的数组上调用Array.reduce [英] Calling Array.reduce on an array with a single element in Javascript
问题描述
在空数组上调用reduce会抛出 TypeError
,这是完全可以理解的,并且有助于捕获错误。但是,当我在其中具有单个项的数组上调用它时,该行为使我感到困惑:
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"
我知道reduce并不意味着要在这样的数组上使用,但是我发现仅返回元素而不调用回调或引发错误至少很奇怪。
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.
此外,MDN文档指出,回调是对数组中的每个值执行四个参数:。
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?
推荐答案
该回调应该是二进制函数(即,该函数需要两个参数进行操作,另外两个参数还包含 currentIndex
和原始的 array
)。
The callback is supposed to be a "binary function" (i.e. one that takes two arguments to operate on, plus the additional two arguments that hold the currentIndex
and the original array
).
如果仅提供一个元素,则将 currentValue
或 previousValue
的未定义值传递给回调,可能导致运行时错误。
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.
因此设计假定仅给定一个值(wh以太是一个空数组,一个 initialValue
或一个只有一个值且没有 initialValue
的数组)最好不要完全调用回调。
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.
这篇关于在Javascript中使用单个元素的数组上调用Array.reduce的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!