【发布时间】:2019-03-08 17:13:58
【问题描述】:
const item = {
id: 'item1',
children: [
{ id: 'item1-1',
children: [
{ id: 'item1-1-1' },
{ id: 'item1-1-2' },
{ id: 'item1-1-3' },
]
},
{ id: 'item1-2',
children: [
{ id: 'item1-2-1' }
]
}
]
}
这样,
function getLevelOfId(){
...
}
getLevelOfId('item1') =====> return 1
getLevelOfId('item1-2') =====> return 2
getLevelOfId('item1-1-1') =====> return 3
getLevelOfId('item1-1-2') =====> return 3
如何使用 JavaScript 获取特定对象的深度?
不使用id 字符串。比如('item1-2').split('-').length 因为每个对象都有随机的id。有没有简单的方法?
【问题讨论】:
-
嗨!请使用tour(您将获得徽章!)并通读help center,尤其是How do I ask a good question? 您最好的选择是进行研究,search 以获取有关 SO 的相关主题,然后试一试. (您可能想要使用递归。)如果在进行更多研究和搜索后您遇到困难并且无法摆脱困境,请发布您的尝试minimal reproducible example并具体说出你卡在哪里。人们会很乐意提供帮助。
-
@SouritraDasGupta 不一样。这个问题是关于
maximum depth的,这是关于specific depth的。
标签: javascript