繁体   English   中英

递归函数在JavaScript中返回空列表

[英]Recursive function return empty list in JavaScript

function getLineItemList(quotationItemElements, checkedLineItemIds) {
var lineItemList = [];
quotationItemElements.children.forEach(function (quotElement, index) {
    if(!parseBoolean(quotElement.isGroup)){
        checkedLineItemIds.forEach(function (checkedId, index) {
            if(quotElement.id == checkedId){
                lineItemList.push(quotElement);
            }
        });
    }else {
        if(quotElement.children.length > 0){
            getLineItemList(quotElement, checkedLineItemIds);
        }
    }
});
return lineItemList;
}
function parseBoolean(str) {
  return /true/i.test(str);
}

我在不同级别的JavaScript列表中具有相同的数据层次结构,而不是显式循环任何级别,而是使用递归调用(幸运的是,这工作正常),但函数始终返回空列表。

JSON数据

您没有捕获递归调用的返回值:

    if(quotElement.children.length > 0){
      /* nobody capture this */  getLineItemList(quotElement, checkedLineItemIds);
    }

您应该将其与lineItemList 因此, lineItemList保持其声明的方式,这是一个空数组。 如果至少quotElement.isGroup一个返回true,则可能不是这样,但是如果没有任何示例输入,我们将quotElement.isGroup

您在函数内部定义lineItemList ,这意味着您每次调用该函数时都从一个空数组开始。 您将需要将数组作为参数传递给函数,还需要return getLineItemList函数的结果。

尝试这个:

function getLineItemList(quotationItemElements, checkedLineItemIds, lineItemList) {
    var lineItemList = lineItemList || [];
    quotationItemElements.children.forEach(function (quotElement, index) {
        if(!parseBoolean(quotElement.isGroup)){
            checkedLineItemIds.forEach(function (checkedId, index) {
                if(quotElement.id == checkedId){
                    lineItemList.push(quotElement);
                }
            });
        }else {
            if(quotElement.children.length > 0){
                return getLineItemList(quotElement, checkedLineItemIds, lineItemList);
            }
        }
    });
    return lineItemList;
}

暂无
暂无

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

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