js面试题:实现dom结构转换成对象

本文探讨了一个常见的JavaScript面试题,即如何将DOM结构转换为JavaScript对象。通过递归方法,不仅可以实现转换,还能在转换过程中计算节点总数、最大深度和最多子节点数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

面试题

将以下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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值