Array contains elements, but length === 0 [duplicate]

191
September 07, 2017, at 8:56 PM

This question already has an answer here:

  • How do I return the response from an asynchronous call? 21 answers
  • Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference 6 answers

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

READ ALSO
Update record in jquery when im using localstorage

Update record in jquery when im using localstorage

I just started jQuery and JavascriptI want to update one record in localstorage when I hit edit button

244
jQuery adding multiple classes

jQuery adding multiple classes

The goal is to add the two classes to any divs with the classtitle

322
Fire function if input value is < 0.2 in jQuery

Fire function if input value is < 0.2 in jQuery

I'd like to firefocusout() only if myInput

327