简体   繁体   中英

push function with javascript doesn't work in this place

var members = ['herpaderpus', 'turtles_head', 'nubstep_rs', 'ardens_fide', 'newending', 'pve_bros', 'rsphilippe', 'pureismwars', 'smap51', 'iprimal_rs', 'im_mr_bloo', 'mrknowles100', 'aikohero', 'cowsbelieve', 'dombo_12', 'diovista', 'mrpixels17'];
var memberData = [];

$.each(members, function(index, member) {
    $.getJSON('https://api.twitch.tv/kraken/users/' + member + '?callback=?', function(d) {
        if(d.status == 404) {}
        else {
            var data = [];
            data[0] = member;
            data[1] = d.display_name;
            memberData.push(data[0]);
                $.getJSON('https://api.twitch.tv/kraken/streams/' + data[0] + '?callback=?', function(d) {
                    if(d.stream != null) { 
                    $( "#player" ).append( "<img src='http://pso-clan.com/twitch/lib/images/online.png'>" + "<a target='_blank' href='http://www.twitch.tv/" + data[0] + "'>" + data[1] + "</a>" + " - Viewers: " + d.stream.viewers + "<br>" );
                    }
              else {
                    $( "#offline" ).append( "<img src='http://pso-clan.com/twitch/lib/images/offline.png'>" + "<a target='_blank' href='http://www.twitch.tv/" + data[0] + "'>" + data[1] + "</a> - Offline<br>" );

                    }

            });
        }   
    });
 }); alert(memberData[0]);   

I don't seem to be able to call

memberData.push(data[0]);

in the place where it's right now, the alert just show undefined. Why doesn't it properly push the member to the memberData array?

You're actually incorrect - where you're using .push() is just fine (in the callback of your first $.getJSON() request).

Where you're alerting it, however is not, because this is an asynchronous request, whereby the alert occurs before the first ajax request is complete.

Take a look at the console output here: http://jsfiddle.net/remus/spSxE/ -- you'll see that undefined appears before any of the array push logging.

Options:

  • Rewrite your method to use parallel ajax requests like the solution here
  • Write the necessary DOM update functions (or whatever you're doing with the results) into the callback of each ajax request so that it is updated after each call completes.

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