Javascript Reduce an empty array

半城伤御伤魂 提交于 2019-12-03 04:50:39

问题


When I reduce the array, I am trying to get the number zero, but I dont clearly understand the behaviour of the function

[].reduce(function(previousValue, currentValue){
  return Number(previousValue) + Number(currentValue);
});

result

TypeError: Reduce of empty array with no initial value

seems that if the array is empty I can't reduce it

[""].reduce(function(previousValue, currentValue){
  return Number(previousValue) + Number(currentValue);
});

result

""

If the only element in the array is an empty string, retrieves an empty string


回答1:


The second parameter is for initial value.

[].reduce(function(previousValue, currentValue){
  return Number(previousValue) + Number(currentValue);
}, 0);

or using ES6:

[].reduce( (previousValue, currentValue) => previousValue + currentValue, 0);



回答2:


Both behaviors are according to the spec.

You cannot reduce an empty array unless you explicitly provide an initial "accumulated" value as the second argument:

If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second. It is a TypeError if the array contains no elements and initialValue is not provided.

If the array has at least one element then providing an initial value is optional. However, if one is not provided then the first element of the array is used as the initial value and reduce continues to process the rest of the array elements by invoking your callback. In your case the array only contains a single element, so that element becomes the initial value and also final value, since there are no more elements to be processed through the callback.



来源:https://stackoverflow.com/questions/23359173/javascript-reduce-an-empty-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!