79

Can anybody tell me why the loop did not stop after the 5 entry?

http://jsbin.com/ucuqot/edit#preview


$(document).ready(function()
{
  someArray = new Array();
  someArray[0] = 't5';
  someArray[1] = 'z12';
  someArray[2] = 'b88';
  someArray[3] = 's55';
  someArray[4] = 'e51';
  someArray[5] = 'o322';
  someArray[6] = 'i22';
  someArray[7] = 'k954';  

  var test =  findXX('o322');   

});

function findXX(word)
{  
  $.each(someArray, function(i)
  {
    $('body').append('-> '+i+'<br />');
    if(someArray[i] == 'someArray')
    {
      return someArray[i]; //<--- did not stop the loop!
    }   
  });  
}
jkdev
  • 11,360
  • 15
  • 54
  • 77
user970727
  • 1,947
  • 4
  • 22
  • 28

6 Answers6

179

Because when you use a return statement inside an each loop, a "non-false" value will act as a continue, whereas false will act as a break. You will need to return false from the each function. Something like this:

function findXX(word) {
    var toReturn; 
    $.each(someArray, function(i) {
        $('body').append('-> '+i+'<br />');
        if(someArray[i] == word) {
            toReturn = someArray[i];
            return false;
        }   
    }); 
    return toReturn; 
}

From the docs:

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • 1
    why dont you use the integrated `function(i,n)` ? – Royi Namir Nov 22 '11 at 09:23
  • Because I just used the code the OP posted in the question and changed the `return`. – James Allardice Nov 22 '11 at 09:24
  • @user970727 - In that example you don't have the `return` statement in the `each` loop at all... Here's an updated example: http://jsbin.com/ucuqot/5/edit – James Allardice Nov 22 '11 at 09:25
  • 1
    @JamesAllardice didn't work for me,at "return=false;" it is exiting the loop alright but later propagating to the statement "return toReturn;" where in my instance i'm returning "true".so true is always returned even if "return = false" is executed – pavan kumar Mar 23 '17 at 10:52
  • Why is like that? you would think, return some value would imply break out of the loop. – kiwicomb123 Mar 31 '17 at 09:46
3

modified $.each function

$.fn.eachReturn = function(arr, callback) {
   var result = null;
   $.each(arr, function(index, value){
       var test = callback(index, value);
       if (test) {
           result = test;
           return false;
       }
   });
   return result ;
}

it will break loop on non-false/non-empty result and return it back, so in your case it would be

return $.eachReturn(someArray, function(i){
    ...
Peter
  • 16,453
  • 8
  • 51
  • 77
1

here :

http://jsbin.com/ucuqot/3/edit

function findXX(word)
{  
  $.each(someArray, function(i,n)
  {
    $('body').append('-> '+i+'<br />');
    if(n == word)
    {
      return false;
    }   
  });  
}
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
0

Try this ...

  someArray = new Array();
  someArray[0] = 't5';
  someArray[1] = 'z12';
  someArray[2] = 'b88';
  someArray[3] = 's55';
  someArray[4] = 'e51';
  someArray[5] = 'o322';
  someArray[6] = 'i22';
  someArray[7] = 'k954';  

  var test =  findXX('o322'); 
  console.log(test);



function findXX(word)
{  
  for(var i in someArray){


    if(someArray[i] == word)
    {
      return someArray[i]; //<---  stop the loop!
    }   
  }
}
TZHX
  • 5,291
  • 15
  • 47
  • 56
sangeeth kumar
  • 319
  • 2
  • 7
  • 23
0

"We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration."

from http://api.jquery.com/jquery.each/

Yea, this is old BUT, JUST to answer the question, this can be a bit simpler:

function findXX(word) {
  $.each(someArray, function(index, value) {
    $('body').append('-> ' + index + ":" + value + '<br />');
    return !(value == word);
  });
}
$(function() {
  someArray = new Array();
  someArray[0] = 't5';
  someArray[1] = 'z12';
  someArray[2] = 'b88';
  someArray[3] = 's55';
  someArray[4] = 'e51';
  someArray[5] = 'o322';
  someArray[6] = 'i22';
  someArray[7] = 'k954';
  findXX('o322');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

A bit more with comments:

function findXX(myA, word) {
  let br = '<br />';//create once
  let myHolder = $("<div />");//get a holder to not hit DOM a lot
  let found = false;//default return
  $.each(myA, function(index, value) {
    found = (value == word);
    myHolder.append('-> ' + index + ":" + value + br);
    return !found;
  });
  $('body').append(myHolder.html());// hit DOM once
  return found;
}
$(function() {
  // no horrid global array, easier array setup;
  let someArray = ['t5', 'z12', 'b88', 's55', 'e51', 'o322', 'i22', 'k954'];
  // pass the array and the value we want to find, return back a value
  let test = findXX(someArray, 'o322');
  $('body').append("<div>Found:" + test + "</div>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

NOTE: array .includes() may better suit here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Or just .find() to get that https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
0

Rather than setting a flag, it could be more elegant to use JavaScript's Array.prototype.find to find the matching item in the array. The loop will end as soon as a truthy value is returned from the callback, and the array value during that iteration will be the .find call's return value:

function findXX(word) {
    return someArray.find((item, i) => {
        $('body').append('-> '+i+'<br />');
        return item === word;
    }); 
}

const someArray = new Array();
someArray[0] = 't5';
someArray[1] = 'z12';
someArray[2] = 'b88';
someArray[3] = 's55';
someArray[4] = 'e51';
someArray[5] = 'o322';
someArray[6] = 'i22';
someArray[7] = 'k954';

var test = findXX('o322');
console.log('found word:', test);

function findXX(word) {
  return someArray.find((item, i) => {
    $('body').append('-> ' + i + '<br />');
    return item === word;
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320