我正在尝试访问下面列出的这些嵌套数组中的关键“孩子”。我想要一个总数,有多少个孩子。我对编码很陌生,我一直在尝试一些事情,但一直无法解决问题。有帮助吗?
另外,我想使用 reduce 方法来完成这个任务,谢谢!
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 selectChildren = arr.reduce((acc, c)=>{
console.log('this is c', c)
console.log('this is acc', acc)
acc + c.children.length()
console.log('this is acc2', acc)
return acc
}, 0)
console.log(selectChildren)
};
countNumberOfChildren(characters)
将您的 countNumberOfChildren 函数编辑为
const countNumberOfChildren = (arr) => {
const selectChildren = arr.reduce((acc, c) => acc + (c.children ? c.children.length : 0), 0);
return selectChildren;
};
在这里,我们首先检查当前元素 (c) 中是否存在名为“children”的属性。如果存在则将其长度添加到 acc 否则添加 0.
问题在于
acc + c.children.length()
不会更改 acc
变量并且 .length
不是函数,它是属性。此外,所以元素可能没有 .children
属性。
您可以将整个
.reduce()
调用压缩成一行,并使用 optional chaining 和 null coalescing 来处理没有像这样的 .children
数组的元素:
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 numChildren = characters.reduce((acc, curr) => acc + (curr.children?.length ?? 0), 0);
console.log(numChildren);