You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用reduce统计嵌套对象children总数失败,求解决方案

如何用reduce统计嵌套数组中children的总数

你的代码存在几个关键问题,导致无法得到预期结果,具体修正点和正确实现如下:

问题分析

  • 数组length是属性而非方法:你写了c.children.length(),但数组长度是通过length属性获取的,加括号会触发错误(因为length不是函数)。
  • 未处理无children属性的元素:数组里的Sansa和Jon对象没有children键,直接访问c.children会抛出Cannot read properties of undefined错误,必须先判断属性是否存在。
  • 未更新累加器值:你计算了acc + ...但没有将结果赋值给acc或返回该值,导致acc始终保持初始的0,最终结果自然为0。

修正后的代码

const characters = [
  {
    name: 'Eddard',
    spouse: 'Catelyn',
    children: ['Robb', 'Sansa', 'Arya', 'Bran', 'Rickon'],
    house: 'Stark',
  },
  {
    name: 'Jon',
    spouse: 'Lysa',
    children: ['Robin'],
    house: 'Arryn',
  },
  {
    name: 'Cersei',
    spouse: 'Robert',
    children: ['Joffrey', 'Myrcella', 'Tommen'],
    house: 'Lannister',
  },
  {
    name: 'Daenarys',
    spouse: 'Khal Drogo',
    children: ['Drogon', 'Rhaegal', 'Viserion'],
    house: 'Targaryen',
  },
  {
    name: 'Mace',
    spouse: 'Alerie',
    children: ['Margaery', 'Loras'],
    house: 'Tyrell',
  },
  {
    name: 'Sansa',
    spouse: 'Tyrion',
    house: 'Stark',
  },
  {
    name: 'Jon',
    spouse: null,
    house: 'Snow',
  },
];

const countNumberOfChildren = (arr) => {
  const total = arr.reduce((acc, current) => {
    // 检查当前对象是否有children属性,有则取长度,无则加0
    const childCount = current.children ? current.children.length : 0;
    // 返回更新后的累加器
    return acc + childCount;
  }, 0);
  console.log(total); // 输出:14
};

countNumberOfChildren(characters)

简化写法(ES6可选链)

可以用可选链操作符简化属性存在性判断,代码更简洁:

const childCount = current.children?.length || 0;

内容的提问来源于stack exchange,提问作者Avreeland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 19:58:12