0

This code returns an array of strings:

var getCitiesList = function (url, callback) {
    var citiesList = [];
    var search = function (needSearch,whereSearch) {
        var re = new RegExp(needSearch,'ig'),
            matched =  whereSearch.match(re); //возвращает массив совпадений
        return matched !== null;
    };
    $.getJSON(url)
        .done(function (data) {
            $.each(data, function (index, value) {
                if (search(input.val(), value.City)) {
                       citiesList.push(value.City);
                    }
            });
        });
    return citiesList;
};

When I call it here, it is looks like empty array, but contains elements, array.length === 0

  input.keyup(function () {
    var cities = getCitiesList('../kladr.json');
    console.log(cities); //[] but contains elements
    console.log(cities.length);//0
});

How it looks in browser

Lev Vysokiy
  • 73
  • 1
  • 5
  • 1
    When you `console.log()` your array **it is empty yes** because he asynchronous call you made hasn't be resolved yet. And so because it is asynchronous, the two `console.log()`s will not yet for the response thus logging `[]` and `0`. Now the proper way to do it is using callbacks functions or Promises. Both ways, it will allow you to run a function **when and only when** the data is received. The jQuery library comes in with the method [`done()`](https://api.jquery.com/deferred.done/) that will allow you to do just that. – Ivan Sep 07 '17 at 13:40
  • $.getJSON(url) .done(function (data) { $.each(data, function (index, value) { if (search(input.val(), value.City)) { citiesList.push(value.City); } }); }); I wrote a code like this. It has a very weird behavior. Sometimes it logs Array(length), sometimes [ ], but elements inside. – Lev Vysokiy Sep 07 '17 at 15:40

0 Answers0