我有一個資料,其中鍵count出現 6 次并且是嵌套的。我正在嘗試用以下邏輯計算它出現的次數,但有點接近它沒有得到確切的結果。
問題是我得到安慰的孩子值是 7。但最終計數始終是 1,我不知道為什么我得到 1。任何幫助!
let data = [{
"id": "1",
"child": [
{
"id": "12",
"child": [
{
"id": "123",
"child": [
{
"id": "1234"
}
]
}
]
},
{
"id": "2",
"child": [
{
"id": "22"
}
]
},
{
"id": "3"
},
{
"id": "4",
"child": [
{
"id": "42",
"child": [
{
"id": "43"
}
]
}
]
}
]
}]
const countChild = (arr,cnt = 0) => {
for (const {child} of arr) {
cnt = cnt 1
console.log("child",cnt)
if(child) countChild(child, cnt)
}
return cnt;
};
console.log("Final count",countChild(data))
uj5u.com熱心網友回復:
我會為此推薦一個reduce功能:
const countData = (arr: any) => {
return arr.reduce((results: number, elm: any) => {
if (!!elm.child) {
results = (1 countData(elm.child));
}
return results;
}, 0);
};
但是如果你仍然想使用你的功能,它需要進行如下調整:
const countChild = (arr,cnt = 0) => {
for (const {child} of arr) {
if (child)
cnt = 1 countChild(child, cnt);
console.log("child",cnt)
}
return cnt;
};
uj5u.com熱心網友回復:
你可以做這樣的事情
let data = [{
"id": "1",
"child": [
{
"id": "12",
"child": [
{
"id": "123",
"child": [
{
"id": "1234"
}
]
}
]
},
{
"id": "2",
"child": [
{
"id": "22"
}
]
},
{
"id": "3"
},
{
"id": "4",
"child": [
{
"id": "42",
"child": [
{
"id": "43"
}
]
}
]
}
]
}]
const flatChild = (arr) =>
arr.flatMap(({id, child}) => [id, ...flatChild(child || [])] )
const countChild = arr => flatChild(arr).length
console.log("Final count", countChild(data))
uj5u.com熱心網友回復:
let data = [{
"id": "1",
"child": [
{
"id": "12",
"child": [
{
"id": "123",
"child": [
{
"id": "1234"
}
]
}
]
},
{
"id": "2",
"child": [
{
"id": "22"
}
]
},
{
"id": "3"
},
{
"id": "4",
"child": [
{
"id": "42",
"child": [
{
"id": "43"
}
]
}
]
}
]
}];
let cnt = 0;
const countChild = (arr) => {
for (const {child} of arr) {
cnt = cnt 1;
console.log("child",cnt);
if(child) countChild(child);
}
return cnt;
};
console.log("Final count",countChild(data));
這里只是將 cnt 放在全域范圍內,這樣 JS 就不會為每個遞回函式制作本地副本
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/526610.html
標籤:javascript数组
