[12 , 3, 4, [5], [[6], [7]]].getLevel()获取当前数组最深层级
Array.prototype.getLevel = function () {
let max = 0
const list = this
const stack = [list]
while(stack.length > 0) {
const data = stack.pop()
for(let i=0; i<data.length; i++) {
let item = data[i]
if (Array.isArray(item)) {
item.level = (data.level || 1) + 1
max = Math.max(item.level, max)
stack.push(item)
}
}
}
return max
}
const a1 = [1, 2, [1], [1, [2, [3]]]]
const a2 = [12, 3, [[6], [7, [7, [66]]], [7]], 4, [5]]
console.log(a1.getLevel(), '1111111') //4
console.log(a2.getLevel(), '2222222') //5