从命名空间中使用递归函数时“递归太多”

时间:2012-11-16 15:00:04

标签: javascript jquery recursion javascript-namespaces

我在javascript中使用了一个非常好的递归方法,直到我把它放在命名空间中。该函数返回一个元素,该元素具有给定的quoteproduct id作为数组中的id属性。它是一个嵌套数组,这就是函数递归的原因。这是函数声明:

QuoteProductService.getQuoteProduct = function (quoteproductid) {
    var founditem = null;
    $.each(QuoteProductService.QuoteProductConfigurations, function (index, item) {
        if(item.id == quoteproductid) {
            founditem = item;
            return false; // break the $.each if an item is found
        } else {
            founditem = QuoteProductService.getQuoteProduct(item.children, quoteproductid);
            if(founditem != null) return false; // break the $.each if an item is found
        }
    });
    return founditem;
}

这就是我声明命名空间的方式:

var QuoteProductService = QuoteProductService || {};

这是我在函数中使用的命名空间中的数组:

QuoteProductService.QuoteProductConfigurations = [];

页面加载时会填充此数组。

现在,每当我调用该函数时,我都会收到“过多的递归”错误。我究竟做错了什么 ?同样,在将函数和数组放入命名空间之前,此函数仍然有效。

1 个答案:

答案 0 :(得分:3)

我刚刚使用更简单的变量名重写了代码:

var a = {
    b: = [{id: 1}, {id: 2}, {id: 3}]
};
a.get = function( searchId ) {
    var match = null;

    $.each(a.b, function(key, value) {
        if ( value.id === searchId ) {
            // Yes we found the match, break and everything

            match = value;
            return false;
        }
        else {
            match = a.get();

            if ( match ) {
                return false;
            }
        }
    });
    return match;
};

a.get(1) // will return {id: 1}
a.get(2) // will throw recursive error

为什么?

由于您的结构,您始终将$.each指向a.b

因此它是这样的:

  

循环a.b:   a.b [0] .id === searchId?
  好的,一切都是好的回报第一价值

     

如果不是a.b [0] .id === searchId
  循环遍历a.b
  a.b [0] .id === searchId?
  好的,一切都好回报第一价值   如果不是a.b [0] .id === searchId
  循环遍历a.b
  .....

希望你理解:

要解决此问题,您需要指定我们必须循环的数组:

QuoteProductService.getQuoteProduct = function (quoteproductid, loopArray) {
    var founditem = null;

    // if (loopArray) {loopArray = loopArray} else { loopArray=Quote...QuteConfig.. }
    loopArray = loopArray || QuoteProductService.QuoteProductConfigurations;

    $.each(loopArray, function (index, item) {
        if(item.id == quoteproductid) {
            founditem = item;
            return false; // break the $.each if an item is found
        } else {
            founditem = QuoteProductService.getQuoteProduct(quoteproductid, item.children);
            if(founditem != null) return false; // break the $.each if an item is found
        }
    });
    return founditem;
}