Home > Back-end >  The return false in jquery each loop not end the entire function
The return false in jquery each loop not end the entire function

Time:12-23

It seems that the return word in jquery each loop will not end the entire function. Here is the code below. The purpose is, when a value in the array is not a number, it should stop all the function, not only the loop. But it turns out that it will only stop the loop and contiue the other logic below.

In C# or Java, the return word will stop the entire function. Is not desgined like this in JavaScript?

function testMehtod() {
        var itemIds = [];
        $("#confirmOrderItemContainer").find(":checkbox:checked").each(function (i, o) {
            itemIds[i] = $(o).attr('item-id');
            if (isNaN(itemIds[i])) {
                return false;
            } 
        });

        //other logic ...
}

CodePudding user response:

if you need to catch breaking the loop and return false too:

function testMehtod() {
    var itemIds = [];
    var ret = true; // our flag variable with default value - everything is good
    
    $("#confirmOrderItemContainer").find(":checkbox:checked").each(function (i, o) {
        itemIds[i] = $(o).attr('item-id');
        if (isNaN(itemIds[i])) { // not good
            ret = false; // let set flag about it
            return false; // break $.each loop
        } 
    });
    if (ret === false) { // not good? let's leave function
        return false;
    }

    //other logic ...
}
  • Related