首页 > 解决方案 > 使用reduce并跳过其中包含0的数组?

问题描述

[]在空数组 ( )上使用 reduce 时出现 TypeError 。

我不想删除 0 或类似的东西,我宁愿减少只是将 0 返回到该数组。

这是我当前的代码:

function squareSum(numbers) {

  let numList = numbers.map(x => Math.pow(x, 2));

  const sum = numList.reduce((x, y) => {
    return x + y
  }); 
  
  return sum;
}

错误:

TypeError: Reduce of an empty array with no initial value

标签: javascriptarraysdictionarymath

解决方案


传递一个初始值作为reduce方法的第二个参数。

如果您省略了初始值,即 the 的第二个参数,reduce那么 reduce 假定您在第一次迭代时array[0]是您的。yreduce

function squareSum(numbers) {

  let numList = numbers.map(x => Math.pow(x, 2));

  const sum = numList.reduce((x, y) => {
    return x + y
  }, 0); // Change here. Use zero initially
  
  return sum;
}

推荐阅读