Get return from javascript anonymous funcion in each loop(s)

69 views Asked by At

I've never worked with js before and now faced with a problem, how can I do next?

function test()
{
    $(xml).find("strengths").each(function() 
    {
        $(this).each(function() 
        {
            (if some condition)
            {
                 //I want to break out from both each loops at the same time here.
                 // And from main function too!
            }
        });
    });
}

I understand that to stop one loop I just need to return false. But what to do if I have some nested? And how to return from main function?

Thanks all!

2

There are 2 answers

0
A. Wolff On BEST ANSWER

You could use two variables:

function test()
{
    var toContinue = true,
        toReturn;
    $(xml).find("strengths").each(function() 
    {
        $(this).each(function() 
        {
            if("some condition")
            {
                toReturn = {something: "sexy there!"};
                return toContinue = false;
            }
        });
        return toContinue;
    });

    if(toReturn) return toReturn;
    //else do stuff;
}
0
Alex McMillan On

You can use a temporary variable, like so:

function test () {
    $(xml).find("strengths").each(function() {
        var cancel = false;

        $(this).each(function() {
            (if some condition) {
                cancel = true;
                return false;
            }
        });

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