简体   繁体   English

递归函数返回空数组

[英]Recursive function returns empty arrays

This code is meant to get all sub-elements and its children into one array. 该代码旨在将所有子元素及其子元素放入一个数组中。 However it returns bunch of empty arrays. 但是,它返回一堆空数组。

function get_independent_elements_from(element) {

    var independent_elements = [];

    if (element.hasChildNodes()) {
        var children = element.children;

        for (let child of children) {
            independent_elements = independent_elements.concat(get_independent_elements_from(child));
        }
    } else {
        independent_elements.push(element);
    }

    return independent_elements;
}

Whilst your new code does appear to work, you could also get the browser to do the heavy lifting for you without recursion: 尽管您的新代码确实可以使用,但您也可以让浏览器为您完成繁重的工作,而无需递归:

function getLeafNodes(el) {
    let nl = el.querySelectorAll('*');
    return [].filter.call(nl, x => !x.firstChild);
}

Here's a potentially more efficient recursive version which just closes over a single array and handles the recursion internally: 这是一个可能更有效的递归版本,它仅关闭单个数组并在内部处理递归:

function getLeadNodes(el) {
    let r = [];
    (function loop(x) {
        if (x.children.length) {
            [].forEach.call(x.children, loop);
        } else {
            r.push(x);
        }
    })(el);
    return r;
}

If the element like this: 如果元素是这样的:

<p>hello world</p>

element.hasChildNodes() will return ture,but element.children return a empty HTMLCollection. element.hasChildNodes()将返回ture,但是element.children返回空的HTMLCollection。

You can change the if condition to take a try. 您可以更改if条件进行尝试。

if (element.children.length) { xxx }

thank you to give advice or comments to me. 谢谢您给我建议或意见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM