gpt4 book ai didi

javascript - 从命名空间中使用递归函数时为 "Too much recursion"

转载 作者:行者123 更新时间:2023-11-30 13:12:23 26 4
gpt4 key购买 nike

我在 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 = [];

该数组在页面加载时填充。

现在,每当我调用该函数时,都会收到“太多递归”错误。我究竟做错了什么 ?同样,这个函数在我将函数和数组放入命名空间之前就起作用了。

最佳答案

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

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

因此它是这样的:

Loop over a.b: a.b[0].id === searchId ?
Ok everything is good return first value

if not a.b[0].id === searchId
Loop over a.b
a.b[0].id === searchId ?
Ok everything is good return first value
if not a.b[0].id === searchId
Loop over 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;
}

关于javascript - 从命名空间中使用递归函数时为 "Too much recursion",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13419098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com