也许你遇到过‘拍平数组’这样的面试题,但如果是求数组的最大深度捏。
‘拍平数组’的各种方法见笔者这篇文章即可:juejin.cn/post/699776…
如果要求最大深度,就要在递归参数里添加深度值,这也是最经典最基础的递归传参了。
`
//求数组深度
const arrayDepth = function (arr) {
let count = 0;
let res = [];
const help = function (arr, dep) {
for (let val of arr) {
if (val instanceof Array) {
help(val, dep + 1);
} else {
res.push(val);
count = Math.max(count, dep)
}
}
}
help(arr, 1);
return count;
}
console.log(arrayDepth([[1], [[1, 2]], [[[[1, 2, 3]]]]]));
记录记录!