Javascript减少一个空数组

agu*_*ina 90 javascript arrays ecmascript-5

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

[].reduce(function(previousValue, currentValue){
  return Number(previousValue) + Number(currentValue);
});
Run Code Online (Sandbox Code Playgroud)

结果

TypeError: Reduce of empty array with no initial value
Run Code Online (Sandbox Code Playgroud)

似乎如果数组是空的我无法减少它

[""].reduce(function(previousValue, currentValue){
  return Number(previousValue) + Number(currentValue);
});
Run Code Online (Sandbox Code Playgroud)

结果

""
Run Code Online (Sandbox Code Playgroud)

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

xda*_*azz 193

第二个参数是初始值.

[].reduce(function(previousValue, currentValue){
  return Number(previousValue) + Number(currentValue);
}, 0);
Run Code Online (Sandbox Code Playgroud)

或使用ES6:

[].reduce( (previousValue, currentValue) => previousValue + currentValue, 0);
Run Code Online (Sandbox Code Playgroud)

  • 我们肯定需要 stackoverflow 中的 <3 表情符号 (6认同)

Jon*_*Jon 22

这两种行为都符合规范.

reduce除非您明确提供初始"累积"值作为第二个参数,否则不能为空数组:

如果没有提供initialValue,则previousValue将等于数组中的第一个值,currentValue将等于第二个值.如果数组不包含元素且未提供initialValue,则为TypeError.

如果数组至少有一个元素,则提供初始值是可选的.但是,如果未提供,则将数组的第一个元素用作初始值,并reduce通过调用回调继续处理其余的数组元素.在您的情况下,数组只包含一个元素,因此该元素将成为初始值和最终值,因为不再有通过回调处理的元素.