Javascript 减少一个空数组 [英] Javascript Reduce an empty array
本文介绍了Javascript 减少一个空数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我减少数组时,我试图得到数字零,但我不清楚函数的行为
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);
});
结果
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);
});
结果
""
如果数组中唯一的元素是空字符串,则检索空字符串
If the only element in the array is an empty string, retrieves an empty string
推荐答案
第二个参数为初始值.
The second parameter is for initial value.
[].reduce(function(previousValue, currentValue){
return Number(previousValue) + Number(currentValue);
}, 0);
或使用 ES6:
[].reduce( (previousValue, currentValue) => previousValue + currentValue, 0);
这篇关于Javascript 减少一个空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文