gpt4 book ai didi

javascript - 在javascript递归函数中增加一个参数

转载 作者:行者123 更新时间:2023-11-30 07:48:44 25 4
gpt4 key购买 nike

我将以下数据存储在一个变量中:

let categories = [
{
name: "a",
selected: false,
nodes: [
{
name: "aa",
selected: false
},
{
name: "ab",
selected: true
},
{
name: "ac",
selected: true
},
{
name: "ad",
selected: false
}
]
},
{
name: "b",
selected: false,
nodes: [
{
name: "ba",
selected: false
},
{
name: "bb",
selected: true
},
{
name: "bc",
selected: true
},
{
name: "bd",
selected: false
}
]
}
];

我想统计有多少项目selected = true
所以我创建了以下函数:

function getSelected(categories, counter = 0) {
for (let index = 0; index < categories.length; index++) {
const category = categories[index];
if (category.selected) {
counter++;
}
if (category.nodes && category.nodes.length) {
category.nodes.forEach(cat => getSelected([cat], counter));
}
}
return counter;
}

但它总是返回0

A working jsFiddle

最佳答案

您可以对节点进行递归归约并计算已选择

const
countSelected = (s, o) => (o.nodes || []).reduce(countSelected, s + o.selected);

let categories = [{ name: "a", selected: false, nodes: [{ name: "aa", selected: false }, { name: "ab", selected: true }, { name: "ac", selected: true }, { name: "ad", selected: false }] }, { name: "b", selected: false, nodes: [{ name: "ba", selected: false }, { name: "bb", selected: true }, { name: "bc", selected: true }, { name: "bd", selected: false }] }],
count = categories.reduce(countSelected, 0);

console.log(count);

关于javascript - 在javascript递归函数中增加一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59489569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com