Open In App

How to skip to next iteration in jQuery.each() util ?

jQuery each() function allows us to loop through different datasets such as arrays or objects. jQuery.each() is one of the most used functions in jQuery.

Syntax:



$(selector).each(function(index, element))
$.each(function(index))

$.each() is essentially a drop-in replacement of a traditional for or for..in loop.

Example 1: This example skipping step 4 to next iteration i.e. Step 5.






<!DOCTYPE html>
<html>
  
<head>
    <title>jQuery.each() method</title>
    <script src=
    </script>
</head>
  
<body>
    <script>
        var arr = ["Step1", "Step2", 
            "Step3", "Step4", "Step5"];
              
        $.each(arr, function (i) {
            if (arr[i] === "Step4") {
                return;
            }
            document.write(arr[i] + ' ');
        });
    </script>
</body>
  
</html>

Output:

Step1 Step2 Step3 Step5

Explanation: In the above code, you can see that when the iteration comes at “i=4” then the “if” condition becomes “true” that returns a non-false value. So it skips the next iteration i.e. Step 4.

Example 2:




<!DOCTYPE html>
<html>
  
<head>
    <title>jQuery.each() method</title>
    <script src=
    </script>
</head>
  
<body>
    <script>
        var arr = [1, 2, 3, 4, 5];
        $.each(arr, function (i) {
            if (arr[i] === 3) {
                return true;
            }
            document.write(arr[i] + ' ');
        });
    </script>
</body>
  
</html>

Output:

1 2 4 5

Article Tags :