calcChildrenLength
统计数组中所有节点子集合总长度
引入版本
0.55.0
Demo
ts
import { calcChildrenLength } from '@wyfex/iutils'
const treeData = [
{
id: 1,
children: [
{ id: 11, children: [111, 112] },
{ id: 12, children: [] }
]
},
{
id: 2,
children: [1, 2, 3]
}
]
console.log('===== 测试1:不开启递归 deep=false =====')
// 只统计第一层children长度:2 + 3 = 5
console.log('结果:', calcChildrenLength(treeData)) // 5
console.log('===== 测试2:开启递归 deep=true =====')
// 第一层:2+3;深层 [111,112] 长度2 => 2+3+2 =7
console.log('结果:', calcChildrenLength(treeData, { deep: true })) //7
console.log('\n===== 测试3:自定义childrenKey =====')
const customKeyData = [
{ id: 1, subs: [1, 2] },
{ id: 2, subs: [1] }
]
console.log(
'结果:',
calcChildrenLength(customKeyData, { childrenKey: 'subs' })
) //3
console.log('\n===== 测试4:传入非数组 =====')
console.log('结果:', calcChildrenLength({ id: 1 }, { deep: true })) //0
console.log('\n===== 测试5:空数组 =====')
console.log('结果:', calcChildrenLength([], { deep: true })) //0
console.log('\n===== 测试6:节点不存在子字段 =====')
const noChildData = [{ id: 1 }, { id: 2, children: null }]
console.log('结果:', calcChildrenLength(noChildData, { deep: true })) //0
console.log('\n===== 测试7:统计二维数组 =====')
console.log(
'结果:',
calcChildrenLength([
[1, 2],
[3, 4, 5]
])
) // 5
console.log('\n===== 测试8:统计多维数组 =====')
console.log(
'结果:',
calcChildrenLength(
[
[[1], [2, 3]],
[4, 5]
],
{ deep: true }
)
) // 7