-2

I'm little confused by behaviour of my functions in JQuery. The thing is that is_airport function decides, whether the location is an airport using JSON of airports.

Everything seems to work correctly, JSON is correctly parsed etc. As you can see there is a loop which is used for detecting, whether the destination_id is in airports JSON keys. It is. It alerts 'OK' but returns false instead of true.

If there was an AJAX instead of each function, I would expect this behaviour because of async. But why it happens here?

function is_airport(destination_id){
    var json_storage = $("#locations-json");
    var airports = JSON.parse(json_storage.attr("data-airports"));
    $.each(airports,function(id,name){
        console.log(id,destination_id,name);
        if (id==destination_id){
            alert('ok');
            return true
        }
    });
    return false
}

$(document).ready(function () {
    console.log(is_airport(5));)}

Do you know where is the problem?

Milano
  • 18,048
  • 37
  • 153
  • 353

1 Answers1

1

You return true from $.each loop, it acts as continue statement. Instead, set a flag to return:

function is_airport(destination_id) {
  var json_storage = $("#locations-json");
  var airports = JSON.parse(json_storage.attr("data-airports"));
  var toReturn = true; // flag variable
  $.each(airports, function(id, name) {
    console.log(id, destination_id, name);
    if (id == destination_id) {
      alert('ok');
      return toReturn = false; // break each loop btw...
    }
  });
  return !toReturn; // return !flag
}
A. Wolff
  • 74,033
  • 9
  • 94
  • 155