js 获取数组的深度
js 获取数组的深度
通过递归的方法
getDepth(arr, depth) {
var flag = false;
var temp = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i].children instanceof Array) { // 判断是否是数组
for (let j = 0; j < arr[i].children.length; j++) {
temp.push(arr[i].children[j]); // 解析出arr下第一层
}
flag = true;
}
}
if (flag) { // 如果还有数组,则继续解析,直到最后一层有不为数组为止
depth++;
return this.getDepth(temp, depth);
} else {
return depth;
}
}
数据例子:
const arr = [
{
"id": 4,
"name": "沙发",
"children": [
{
"id": 10,
"name": "多人沙发",
"children": [
{
"id": 21,
"name": "双人沙发(一字)",
"children": [],
"content": []
},
{
"id": 22,
"name": "三人沙发(一字)",
"children": [],
"content": []
},
{
"id": 23,
"name": "四人沙发(一字)",
"children": [],
"content": []
},
{
"id": 24,
"name": "L型转角沙发",
"children": [],
"content": []
},
{
"id": 25,
"name": "斜角沙发",
"children": [],
"content": []
},
{
"id": 26,
"name": "U型转角沙发",
"children": [],
"content": []
},
{
"id": 27,
"name": "弧形沙发",
"children": [],
"content": []
}
]
},
{
"id": 11,
"name": "单人沙发",
"children": [
{
"id": 28,
"name": "带扶手沙发",
"children": [],
"content": []
}
]
},
{
"id": 12,
"name": "贵妃榻",
"children": [
{
"id": 29,
"name": "贵妃榻",
"children": [],
"content": []
}
]
},
{
"id": 13,
"name": "沙发床",
"children": [
{
"id": 30,
"name": "沙发床",
"children": [],
"content": []
}
]
}
]
},
{
"id": 14,
"name": "沙发",
"children": [
{
"id": 15,
"name": "多人沙发",
"children": [],
"content": []
},
{
"id": 16,
"name": "单人沙发",
"children": [],
"content": []
},
{
"id": 17,
"name": "L型沙发",
"children": [],
"content": []
},
{
"id": 18,
"name": "懒人沙发",
"children": [],
"content": []
},
{
"id": 19,
"name": "沙发床",
"children": [],
"content": []
},
{
"id": 20,
"name": "儿童沙发",
"children": [],
"content": []
}
]
},
{
"id": 31,
"name": "沙发",
"children": [
{
"id": 32,
"name": "沙发",
"children": [],
"content": []
},
{
"id": 33,
"name": "沙发",
"children": [],
"content": []
},
{
"id": 34,
"name": "沙发",
"children": [],
"content": []
},
{
"id": 35,
"name": "沙发",
"children": [],
"content": []
}
]
},
{
"id": 36,
"name": "沙发",
"children": [
{
"id": 40,
"name": "沙发",
"children": [],
"content": []
},
{
"id": 41,
"name": "沙发",
"children": [],
"content": []
}
]
},
{
"id": 37,
"name": "沙发",
"children": [
{
"id": 42,
"name": "沙发",
"children": [
{
"id": 43,
"name": "沙发",
"children": [],
"content": []
}
]
},
{
"id": 44,
"name": "沙发",
"children": []
},
{
"id": 45,
"name": "沙发",
"children": []
},
{
"id": 46,
"name": "沙发",
"children": []
}
]
},
{
"id": 38,
"name": "沙发",
"children": [],
"content": []
},
{
"id": 39,
"name": "沙发",
"children": [],
"content": []
}
]
调用getDepth(arr, 1)取得数组深度为:3