对象层级计算有递归和迭代两种方法:递归方法使用递归函数,从根节点开始计算每个属性子节点的层级,返回最大深度;迭代方法使用队列,从根节点开始,将每个节点的层级加一,将子节点入队,循环直至队列为空,返回最大层级。例如,对于对象 { a: { b: { c: null, d: null } }, e: null }, 递归方法和迭代方法计算的层级均为 3。

如何计算对象层级
计算对象层级的目的是确定一个对象在对象树中的深度。层级从根节点开始为 0,其子节点层级加 1,依此类推。
方法
计算对象层级有两种常用方法:
递归方法
- 定义递归函数
getDepth(object)。 - 在函数中,如果
object是null,返回 0。 - 对
object的每个属性,递归调用getDepth(object[property]),并将结果加 1。 - 返回最大深度。
迭代方法
- 创建一个队列,将根节点入队。
- 设置层级为 0。
-
循环,直到队列为空:
- 出队第一个节点
node。 - 将
node的层级设置为当前层级。 - 将
node的所有子节点入队。 - 增加当前层级。
- 出队第一个节点
- 返回最大层级。
示例
假设有以下对象:
<code>const object = {
a: {
b: {
c: null,
d: null
}
},
e: null
};</code>递归方法
<code class="js">function getDepth(object) {
if (object === null) {
return 0;
}
let maxDepth = 0;
for (const property in object) {
maxDepth = Math.max(maxDepth, getDepth(object[property]) + 1);
}
return maxDepth;
}
const depth = getDepth(object); // 3</code>迭代方法
<code class="js">function getDepth(object) {
const queue = [object];
let depth = 0;
while (queue.length > 0) {
const node = queue.shift();
node.depth = depth;
for (const property in node) {
if (node[property] !== null) {
queue.push(node[property]);
}
}
depth++;
}
return depth - 1;
}
const depth = getDepth(object); // 3</code>










