2

How to break .each loop in JavaScript,

if(badCatsNames.length > 0)
{
    for (var i = 0; i < badCatsNames.length; i++) {
        var badCatName = badCatsNames[i];

        $("[id$=listAvailableCats] li").each(function (index) {
            if ($(this).text() == badCatName) {
                $(this).appendTo($("[id$=listPurchasingCats]"));
            }
            else {
                $("[id$=listPurchasingCats] li").each(function (index) {
                    if ($(this).text() == badCatName) {
                        $(this).appendTo($("[id$=listAvailableCats]"));
                    }
                });
            }
        });
    } 
}}

What I want

If code finds bad cat name in availabel cats list then break and start again @ for loop

If you can improve code too, please do :)

1
  • 2
    You can break a .each loop by doing return false;. Commented Mar 19, 2014 at 15:11

2 Answers 2

6

return true; will skip the current iteration and head to the next, return false; will leave the each loop completely.

Sign up to request clarification or add additional context in comments.

1 Comment

return true; is to continue; as return false; is to break; :-D
1

you can use return false; to exit a loop at any time.

if(badCatsNames.length > 0)
{
for (var i = 0; i < badCatsNames.length; i++) {
    var badCatName = badCatsNames[i];

    $("[id$=listAvailableCats] li").each(function (index) {
        if ($(this).text() == badCatName) {
            $(this).appendTo($("[id$=listPurchasingCats]"));
        }
        else {
            $("[id$=listPurchasingCats] li").each(function (index) {
                if ($(this).text() == badCatName) {
                    $(this).appendTo($("[id$=listAvailableCats]"));
         return false;
                }
            });
        }
    });
} 
}};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.