目录
1.查询树形节点的最深层级
// 获取树形节点的最深层级
export function getMaxFloor (treeData: any[] = []) {
let max = 0
function each (data: any[] = [], floor: number) {
data.forEach(e => {
e.floor = floor
if (floor > max) {
max = floor
}
if (e.children.length > 0) {
each(e.children, floor + 1)
}
})
}
each(treeData,1)
return max
}
const treeData = [
{
title: 'parent 1',
key: '0-0',
children: [
{
title: 'parent 1-0',
key: '0-0-0',
disabled: true,
children: [
{
title: 'leaf',
key: '0-0-0-0',
disableCheckbox: true,
},
{
title: 'leaf',
key: '0-0-0-1',
},
],
},
{
title: 'parent 1-1',
key: '0-0-1',
children: [{ title: <span style={{ color: '#1890ff' }}>sss</span>, key: '0-0-1-0' }],
},
],
},
];
//调用以上封装好的方法
const maxNum = getMaxFloor(treeData)
//maxNum就是treeData的最深层级
2.递归查找树形节点的某个节点
const loop = (data, key, callback) => {
for (let i = 0; i < data.length; i++) {
if (data[i].key == key) {
return callback(data[i], i, data)
}
if (data[i].children) {
loop(data[i].children, key, callback)
}
}
}
// 所查找到的节点要存储的方法
let Obj
loop(data, dragKey, (item, index, arr) => {
Obj = item
})
// 此时就是Obj对应的要查找的节点
console.log(Obj)
3.查找数组的最深层级
// 计算数组最深层级
const arr = [1,3,3,[4,6,7,[5,6,7,43,[23,4]]]];
function arrayDepth(arr, currDepth = 1) {
let maxDepth = currDepth
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
const depth = arrayDepth(arr[i], currDepth + 1)
maxDepth = Math.max(maxDepth, depth)
}
}
return maxDepth;
}
console.log(`最深层级为:${arrayDepth(arr )}`);
以上 就是封装好的方法,有需要的朋友可以参照一下的!