空数组调用 reduce

空数组调用 reduce 方法的行为和解决方案

问题

空数组调用 reduce() 方法会发生什么?

解答

当空数组调用 reduce() 方法时,如果没有提供初始值,会抛出 TypeError 错误。因为 reduce() 无法从空数组中获取初始累积值。

const emptyArray = [];
const result = emptyArray.reduce((accumulator, currentValue) => accumulator + currentValue);
// TypeError: Reduce of empty array with no initial value

解决方法是提供初始值作为 reduce() 的第二个参数。这样即使数组为空,也会返回初始值。

const emptyArray = [];
const initialValue = 0;
const result = emptyArray.reduce(
  (accumulator, currentValue) => accumulator + currentValue, 
  initialValue
);

console.log(result); // 输出: 0

关键点

  • 空数组调用 reduce() 且未提供初始值时会抛出 TypeError
  • 提供初始值可以避免错误,空数组会直接返回初始值
  • 建议在使用 reduce() 时始终提供初始值,提高代码健壮性