JS计算数组层级(深度)
如果有一个多层嵌套的数组,想要计算其层级(深度),可以使用递归或迭代方法来实现。以下是两种常用的方法示例:
递归方法:
function calculateDepth(arr) {
if (!Array.isArray(arr)) {
return 0; // 如果不是数组,返回0表示不是层级结构
}
let maxDepth = 0;
for (const item of arr) {
const depth = calculateDepth(item);
maxDepth = Math.max(maxDepth, depth);
}
return maxDepth + 1; // 加1表示当前层级
}
const nestedArray = [1, [2, [3, 4], 5], 6];
const depth = calculateDepth(nestedArray);
console.log(`数组的层级是 ${depth}`);
这个递归函数 calculateDepth
接受一个数组作为参数,并递归地计算其深度。对于每个元素,它调用自身,并比较每个子数组的深度,然后返回最大深度加1,以表示当前层级。
迭代方法:
function calculateDepth(arr) {
if (!Array.isArray(arr)) {
return 0;
}
let depth = 0;
let stack = arr.map(item => [item, 1]); // 使用栈来迭代
while (stack.length > 0) {
const [current, currentDepth] = stack.pop();
depth = Math.max(depth, currentDepth);
if (Array.isArray(current)) {
for (const item of current) {
stack.push([item, currentDepth + 1]);
}
}
}
return depth;
}
const nestedArray = [1, [2, [3, 4], 5], 6];
const depth = calculateDepth(nestedArray);
console.log(`数组的层级是 ${depth}`);
这个迭代方法使用了一个栈来处理嵌套数组。它首先将根元素和层级1入栈,然后迭代处理栈中的元素,不断地将子数组和它们的层级入栈,同时更新最大深度。最终,返回最大深度。
无论使用递归还是迭代,这两种方法都可以计算多层嵌套数组的层级深度。可以根据自己的偏好选择其中一种方法来使用。
分类:
前端
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!