开发者社区 问答 正文

Javascript减少一个空数组

当我减少数组时,我试图将数字设为零,但我不清楚地了解函数的行为

[].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); }); 结果

"" 如果数组中唯一的元素是一个空字符串,则检索一个空字符串 问题来源于stack overflow

展开
收起
保持可爱mmm 2020-02-08 12:33:09 468 分享 版权
1 条回答
写回答
取消 提交回答
  • 第二个参数用于初始值。

    [].reduce(function(previousValue, currentValue){ return Number(previousValue) + Number(currentValue); }, 0); 或使用ES6:

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

    2020-02-08 12:33:22
    赞同 展开评论
问答分类:
问答标签:
问答地址: