js如何获取树形数组最深层数目


            getMaxFloor (treeData) {
    
    
                let floor = 0
                let v = this
                let max = 0
                function each (data, floor) {
    
    
                    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
          }
          返回值为:3

注:传入值需是数组,如下:

[
	{
    
    
	  	"label": "广东省",
		"children": [
			{
    
    
				"label": "梅州市",
				"children": [
					{
    
    
						"label": "兴宁市",
						"children": []
					}
				]
			}
		]
	},
	{
    
    "label": "一级2", "children": []},
	{
    
    "label": "一级3", "children": []}
]

若是对象形式,外边用“[]”包裹即可。


	{
    
    
	  	"label": "广东省",
		"children": [
			{
    
    
				"label": "梅州市",
				"children": [
					{
    
    
						"label": "兴宁市",
						"children": []
					}
				]
			}
		]
	},
	{
    
    "label": "一级2", "children": []},
	{
    
    "label": "一级3", "children": []}

猜你喜欢

转载自blog.csdn.net/qq_42931285/article/details/126756822