已知树形结构数据通过递归方式结合Math.max方法计算出树形结构最大层级数。
const treeData = [
{
title: "0-0",
key: "0-0",
children: [
{
title: "0-0-0",
key: "0-0-0",
children: [
{ title: "0-0-0-0", key: "0-0-0-0" },
{ title: "0-0-0-1", key: "0-0-0-1" },
{ title: "0-0-0-2", key: "0-0-0-2" },
],
},
{
title: "0-0-1",
key: "0-0-1",
children: [
{ title: "0-0-1-0", key: "0-0-1-0" },
{ title: "0-0-1-1", key: "0-0-1-1" },
{ title: "0-0-1-2", key: "0-0-1-2" },
],
},
{
title: "0-0-2",
key: "0-0-2",
},
],
},
{
title: "0-1",
key: "0-1",
children: [
{ title: "0-1-0-0", key: "0-1-0-0" },
{ title: "0-1-0-1", key: "0-1-0-1" },
{ title: "0-1-0-2", key: "0-1-0-2" },
],
},
{
title: "0-2",
key: "0-2",
},
];
// 计算方法
const getLevel = (arr) => {
let maxLevel = 0;
(function callBack(arr, level) {
++level;
maxLevel = Math.max(level, maxLevel);
for (let i = 0; i < arr.length; i++) {
let item = arr[i];
if (item.children && item.children.length > 0) {
callBack(item.children, level);
} else {
delete item.children;
}
}
})(arr, 0);
return maxLevel;
};
console.log('treeData最大层级:',getLevel(treeData));
控制台输出结果: treeData最大层级: 3
标签:arr,title,treeData,级数,js,item,树形,key,children
From: https://www.cnblogs.com/ZerlinM/p/17147941.html