如何制作递归方法

问题描述

我正在尝试在javascript中创建递归方法,但创建了无限循环。

我的想法是创建一个递归方法,该方法检查子级数是否少于最大值。

这是我的代码,但是正如我所说,我不知道为什么要创建一个无限循环。

    //function UploadComplete(sender,args) {
    //    var filename = args.get_fileName();
    //    var contentType = args.get_contentType();
    //    var text = "Size of " + filename + " is " + args.get_length() + " bytes";
    //    if (contentType.length > 0) {
    //        text += " and content type is '" + contentType + "'.";
    //    }
    //    document.getElementById('lblInstrucError').innerText = text;
    //}

    function showModalAttachment() {
        $('.modal-body').css('height',$(window).height() * 0.7);
        $("#AttachModal").modal('show');
        $('body').css('overflow','scroll');
    }

    //instruction attachment
    $(function () {
        $("#lnkViewUploadedPdf").click(function () {
            showModalAttachment();
        });
    });

    $(function () {
        $("#lnkViewUploadedXls").click(function () {
            showModalAttachment();
        });
    });

编辑

对不起,我很愚蠢...

dmaExtractor(数据 .children);通过dmaExtractor( child .children);

解决方法

请查看以下代码:

export const checkMaximumChildren = (hierarchy,maximum) => {
    let hasMoreThanMaximumChildren = false;

    if (hierarchy.children.length > maximum) {
        hasMoreThanMaximumChildren = true;
    } else {
        const dmaExtractor = (children) => {
            children.forEach((child) => {
                if (child.children.length > maximum) {
                    hasMoreThanMaximumChildren = true;
                    return hasMoreThanMaximumChildren;
                }

                if (
                    child &&
                    child.children &&
                    Array.isArray(child.children) &&
                    child.children.length > 0
                ) {
                    return dmaExtractor(data.children); // change #1
                }
            });
        };

        if (
            hierarchy &&
            hierarchy.children &&
            Array.isArray(hierarchy.children) &&
            data.children.length > 0
        ) {
            hasMoreThanMaximumChildren = dmaExtractor(hierarchy.children); // change #2
        }
    }

    return hasMoreThanMaximumChildren;
};

无限循环背后的原因可能是内部dmaExtractor方法未返回任何内容。

我在开发控制台中的文档DOM节点上对此进行了测试:

enter image description here

,

也许我在这里遗漏了一些重要的东西,但是为什么不编写一个递归函数来计算层次结构中的节点数,然后用一个函数将其包装以确定它是否不大于最大值呢?

也就是说:

const countKids = (data = []) => 
  data .reduce ((total,node) => total + 1 + countKids (node .children || []),0)

const checkMaximumChildren = (hierarchy,maximum) => 
  countKids (hierarchy) <= maximum

const data = [{id: 1,parentId: null,selected: false,children: [{id: 2,parentId: 1,children: [{id: 3,parentId: 2,children: [{id: 4,parentId: 3,children: []}]}]}]},{id: 1,selected: true,children: []},children: []}]

console .log (countKids (data) )
console .log (checkMaximumChildren (data,5))
console .log (checkMaximumChildren (data,10))