简体   繁体   中英

Strange behaviour with JQuery and Console.log()

I wrote a little JavaScript, which behaviour is unexplainable for me.

var allPois = [];
$.getJSON( "pois.json", function( data ) {
    $.each( data, function( i, poi ) {
        allPois[poi.id] = poi;
    });
    console.log(allPois["abc"]);
});

I basically get a JSON-File and then put all the existing entrys into the 'allPois' variable.
This example works. It displays the object in the console without any problems as expected. But the next one doesn't.

var allPois = [];
$.getJSON( "pois.json", function( data ) {
    $.each( data, function( i, poi ) {
        allPois[poi.id] = poi;
    });
});
console.log(allPois["abc"]);

Notice the position of the console.log()-statement. The console displays 'undefined'. I tested it with Firefox and Chrome. What is the problem here?

Thank you very much!

zuris57

$.getJSON is asynchronous; the execution of the containing function doesn't stop and wait for the Ajax request to complete by default. That's why the callback exists – it's called back when you can actually use the request's response.

It really looks like you should be doing this, by the way:

var allPois = {}; // Object, not array

$.getJSON( "pois.json", function( data ) {
    $.each( data, function( i, poi ) {
        allPois[poi.id] = poi;
    });

    console.log(allPois.abc);
});

getJSON is an AJAX function. The first A in AJAX stands for "Asynchronous". As a general rule, if a function takes a callback, then anything that relies on the result MUST be in that callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM