JQuery jumps out of the each loop using array traversal

  • 2021-08-10 06:44:22
  • OfStack

0. Preface

Maybe we use the loop method of jquery to traverse the array, but when it does not meet the conditions, how to jump out of the current loop? (That is, in the each method, when the conditions are not met, we want break to jump out of the loop body and continue to continue to execute the next loop traversal). We often get used to break and continue in JS, but it has no effect after use, because there are no these two commands in JQuery, which are not its keywords.

1. JQuery each cycle, to realize the functions of break and continue

break--return false; continue-return ture;

2. How does JQuery jump out of the current each loop

The instructions on API only jump out of the whole loop (if you need to exit the each loop, the callback function will return false, and other return values will be ignored.)

return false; -Jump out of all cycles; Equivalent to break effect in javascript. return true; -Jump out of the current cycle and enter the next cycle; Equivalent to continue effect in javascript

The example code is as follows:


$(function (){
 $("input[type='text']").each(function (i){ 
 var _val=$(this).val();
 alert(_val);
 if(_val=='2'){ 
  return false; // Out of the loop 
 }
 })
});

3. The JQuery each method jumps out of the loop and gets the return value

return false: The loop will stop (just like using 'break' in a normal loop). return true: Skip to the next loop (just like using 'continue' in a normal loop).

The code is as follows:


function test(){
var success = false;
$(..).each(function () {
  if (..) {
    success = true;
    return false;
  }
});
 return success ;
}

JQuery is a chain of objects, so $(...). each () returns a collection of objects. each (function () {}): Is a callback function in which results cannot be returned outside the callback function each.


Related articles: