admin管理员组文章数量:1178553
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?
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?
Share Improve this question asked Nov 24, 2015 at 17:32 fatfat 5,5594 gold badges29 silver badges31 bronze badges3 Answers
Reset to default 35The 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
).
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.
If you call reduce
on an array with a single-valued array, it will return the only element in the array because there is no other value to compare, thus the callback function won't be executed.
If you want to execute the callback function even with a single-valued array, then provide an initial value to the reducer as the second argument.
var arr = ['a'];
var initialValue = 'x';
arr.reduce((a,b) => /some operation/, initialValue);
reduce needs to have more than one value to accumulate, you can add a check before
if(arr.length <= 1 ) values = arr[0]??[]
else {
values = arr.reduce( (a, b) => {
return [a,b]
});
}
本文标签: Calling Arrayreduce on an array with a single element in JavascriptStack Overflow
版权声明:本文标题:Calling Array.reduce on an array with a single element in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1737999308a2046952.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论