当我减少数组时,我试图让数字为零,但我不清楚函数的行为
[].reduce(function(previousValue, currentValue){
return Number(previousValue) + Number(currentValue);
});
结果
TypeError: Reduce of empty array with no initial value
似乎如果数组为空我就不能减少它
[""].reduce(function(previousValue, currentValue){
return Number(previousValue) + Number(currentValue);
});
结果
""
如果数组中的唯一元素是一个空字符串,则检索一个空字符串
最佳答案
The second parameter 为初始值。
[].reduce(function(previousValue, currentValue){
return Number(previousValue) + Number(currentValue);
}, 0);
或使用 ES6:
[].reduce( (previousValue, currentValue) => previousValue + currentValue, 0);
关于Javascript减少一个空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23359173/