Leaving the Jqery foreach

Asked

Viewed 162 times

0

I’m having trouble getting out of a foreach when the internal if condition is met, I followed the recommendations of the official Jquery documentation that says to give a return false but still not working, follows the code used:

if (digitado != "") {
    hashModens.forEach(function (item, i) {
        if ((digitado == item.Nome || digitado == item.Node || digitado == item.Mac) && item.MarkerVisible) {
            let infoPosition = { lat: item.Latitude + 0.000008, lng: item.Longitude }

            retornou = true;
            map.setZoom(22);
            map.panTo(new google.maps.LatLng(item.Latitude, item.Longitude));
            item.InfoWindow.setPosition(infoPosition);
            item.InfoWindow.open(map);
            return false;
        }
    });
}

Something is missing, so I can interrupt this foreach?

2 answers

3

It is not possible for a foreach, but you have other alternatives, such as using the function Every, when returning true, it continues, by returning false it to:

hashModens.every(function(item, i) {

  if (Sua_condicao){
     return false;
  } 
  return true;
})
  • Damn cool this method I didn’t know, but I’m using a Map() and it seems that it only exists in arrays :/

  • Yes, for objects jQuery you need to use the $.each as in @fernandosavio’s reply.

3


The method Array.forEach is javascript, you must have confused with the $.each jQuery.

You can use jQuery:

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

$.each(array, (i, num) => {
    console.log(num)
    if (num > 5) return false
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Or use a for:

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for(let i=0, l=array.length ; i<l ; i++) {
  console.log(array[i])
  if (array[i] > 5) break
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.