How to break out of jQuery each Loop

后端 未结 7 2251
遇见更好的自我
遇见更好的自我 2020-11-22 10:04

How do I break out of a jQuery each loop?

I have tried:

 return false;

In the loop but this did not work. Any ideas?

7条回答
  •  半阙折子戏
    2020-11-22 11:01

    I know its quite an old question but I didn't see any answer, which clarify that why and when its possible to break with return.

    I would like to explain it with 2 simple examples:

    1. Example: In this case, we have a simple iteration and we want to break with return true, if we can find the three.

    function canFindThree() {
        for(var i = 0; i < 5; i++) {
            if(i === 3) {
               return true;
            }
        }
    }
    

    if we call this function, it will simply return the true.

    2. Example In this case, we want to iterate with jquery's each function, which takes anonymous function as parameter.

    function canFindThree() {
    
        var result = false;
    
        $.each([1, 2, 3, 4, 5], function(key, value) { 
            if(value === 3) {
                result = true;
                return false; //This will only exit the anonymous function and stop the iteration immediatelly.
            }
        });
    
        return result; //This will exit the function with return true;
    }
    

提交回复
热议问题