使用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
相关产品推荐
相关产品推荐

