1

名前空間に配置するまで、javascriptで再帰メソッドを使用しています。これは完全に正常に機能しました。この関数は、指定されたquoteproductidを配列の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 = [];

この配列は、ページが読み込まれるときに入力されます。

これで、関数を呼び出すたびに、「再帰が多すぎます」というエラーが発生します。私は何を間違っているのですか?繰り返しますが、この関数は、関数と配列を名前空間に配置する前に機能しました。

4

1 に答える 1

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: ab[0].id === searchId ?
わかりましたすべてが良いです最初の値を返します

ab[0].id === searchId でない場合 ab[0].id === searchId
をループしa.b
ますか? ab[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;
}
于 2012-11-16T15:15:40.783 に答える