面试题
将以下dom结构转换成js对象,并输出节点个数,最大深度以及最多子节点数
<html>
<head></head>
<body>
<div>
<span>f</span>
<span>o</span>
<span>o</span>
</div>
</body>
</html>
nodeCounts = 7
maxDepth = 4
maxChildren = 3
{
type: 'HTML'
children: [
{
type: 'HEAD',
children: []
},
{
type: 'BODY',
children: [
{
type: 'DIV',
children: [
{
type: 'SPAN',
children: []
},
{
type: 'SPAN',
children: []
},
{
type: 'SPAN',
children: []
}
]
}
]
}
]
}
实现如下:
通过递归来生成对应的js对象,并在递归过程中获取最大的深度和最多子节点数
function helper(node, res, deep){
if(node.nodeType === 1){
deep++;
let tmp = {}
tmp['type'] = node.tagName
res.push(tmp)
maxChildren = Math.max(res.length, maxChildren)
maxDepth = Math.max(deep, maxDepth )
if(node.childNodes){
tmp['children'] = []
for (let i = 0; i < node.childNodes.length; i++){
helper(node.childNodes[i], tmp['children'], deep)
}
}
}
}
let root = document.getElementsByTagName('html')[0]
let res = []
let nodeCounts = document.getElementsByTagName('*').length
let maxDepth = 0
let maxChildren = 0
helper(root, res, 0)
console.log(nodeCounts); // 7
console.log(maxChildren); // 3
console.log(maxDepth); // 4