Javascript减少一个空数组 [英] Javascript Reduce an empty array

查看:63
本文介绍了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);
});

结果

""

如果数组中唯一的元素是空字符串,则检索为空string

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆