You need to enable JavaScript to run this app. JavaScript中如何动态判断数组的维度数量?
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何动态判断数组的维度数量?

JavaScript 动态计算数组嵌套层级的方案

核心思路通过递归遍历数组元素,每进入一层嵌套层级计数+1,最终取所有子元素的最大层级作为整个数组的层级。

实现代码

function getArrayDepth(target) {
  // 非数组元素层级记为0
  if (!Array.isArray(target)) return 0
  let maxChildDepth = 0
  for (const item of target) {
    const currentDepth = getArrayDepth(item)
    maxChildDepth = Math.max(maxChildDepth, currentDepth)
  }
  // 加上当前数组本身的一层
  return maxChildDepth + 1
}

该方法兼容所有常规数组场景,空数组调用会返回1,符合空数组本身占1层的常规认知,有特殊需求可自行调整边界返回值

测试验证

// 测试用例1
const ary1 = ["a","b",["c","d"],"e",["f","g",["h","i"],"j"]];
console.log(getArrayDepth(ary1)) // Output: 3

// 测试用例2
const ary2 = ["a","b",["c","d"],"e",["f","g","i"]];
console.log(getArrayDepth(ary2)) // Output: 2

// 测试用例3
const ary3 = ["a","b",["c",["d"]],"e",[["f","g",["i","j"]],"k"]];
console.log(getArrayDepth(ary3)) // Output: 4

内容的提问来源于stack exchange,提问作者Rajeshkumar Gone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 01:00:03