Maison  >  Questions et réponses  >  le corps du texte

javascript - Trouver la profondeur maximale de l'arborescence DOM à l'aide de JS natif

Comment trouver la profondeur maximale de l'arborescence DOM en utilisant du js natif ?

过去多啦不再A梦过去多啦不再A梦2662 Il y a quelques jours1313

répondre à tous(2)je répondrai

  • PHP中文网

    PHP中文网2017-07-05 11:09:52

    Implémentation récursive

    J'ai utilisé l'attribut children du nœud dom pour parcourir et récurser

    La routine récursive est : 返回 (1 + 子节点们深度的最大值)

    // map(e => e + 1)([0, 1, 2]) 
    // => 1, 2, 3 
    // 类似于数组的map方法 不过这里柯里化了 
    var map = cb => arr => Array.prototype.map.call(arr, cb); 
    
    // 取数组最大值 
    // max([0, 1, 2])
    // => 2 
    var max = arr => arr.reduce((acc, cur) => {
        if (cur >= acc) return cur; 
        else return acc; 
    }, arr[0]); 
    
    // 递归函数 
    var nextChildren = node => {
        // 基准条件 
        if (node.children.length === 0) return 1; 
        else {
            // 求子节点们的长度 并取最大值 
            var deeps = map(nextChildren)(node.children); 
            
            return 1 + max(deeps); 
        }
    }
    
    // 计算 
    var $body = document.getElementsByTagName('body')[0];
    var deep = nextChildren($body); 
    console.log(deep); 

    Capture d'écran

    répondre
    1
  • 三叔

    三叔2017-07-05 11:09:52

    répondre
    0
  • Annulerrépondre