Leaving the foreach JQery

0

I'm having difficulty getting out of a foreach when the internal if condition is met, I followed the recommendations in the official JQuery documentation that says to give a return false but it still does not work, follow 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;
        }
    });
}

Is something missing, so I can interrupt this foreach?

    
asked by anonymous 17.12.2018 / 13:50

2 answers

3

The method Array.forEach is javascript, you should have confused yourself with jQuery $.each .

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>

Oruseafor:

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
}
    
17.12.2018 / 14:38
3

Not possible for a foreach, but you have other alternatives, such as using the every , returning true, it continues, returning false it to:

hashModens.every(function(item, i) {

  if (Sua_condicao){
     return false;
  } 
  return true;
})
    
17.12.2018 / 14:07