search

Home  >  Q&A  >  body text

javascript - Why can an array with 3 object elements only access the first element?


There are three elements in status expansion
Then status[0] is the object element I push in
Then status [1] and status[2] are all kinds of undefined, why?

The following is the complete code. After trying it several times, I think it has something to do with the variable scope. However, the array variable result is in the outermost layer. Why can't push() inside it be retrieved from the outside?

function getStreamsStatus(channels) {
  var results = [];
  $.each(channels, function(index, channel) {
    var result = [];
    // result.push({ name: channel });
    $.getJSON (
      "https://api.twitch.tv/kraken/streams/" + channel,
      {
        Accept: "application/vnd.twitchtv.v5+json",
        client_id: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        callback: ""
      },
      function(data) {
        result.push(data);
        $.getJSON(
          data._links.channel,
          {
            Accept: "application/vnd.twitchtv.v5+json",
            client_id: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
            callback: ""
          },
          function(channel_data) {
            result.push(channel_data);
            // console.log(result);
            // console.log(result[0]);
            // console.log(result[1]);
          });
        console.log(result);
        console.log(result[0]);
        console.log(result[1]);
      });
    results.push(result);
    // console.log(result);
    // console.log(result[0]);
    // console.log(result[1]);
  });
  return results;
}
PHP中文网PHP中文网2787 days ago624

reply all(4)I'll reply

  • 给我你的怀抱

    给我你的怀抱2017-05-19 10:25:15

    Ajax is an asynchronous process, and the callback function is executed after the data is retrieved
    And your results.push(result) should have been pushed in before the data is retrieved
    So when you check it, it has not yet been Push into the array of data.
    You have to wait until the data is loaded before you can see the data in the console
    The same is true for the previous Ajax nesting

    reply
    0
  • PHPz

    PHPz2017-05-19 10:25:15

    undefined can also be stored in an array, and it also has a length.

    reply
    0
  • 迷茫

    迷茫2017-05-19 10:25:15

    Brother...please take the full screenshot,

    Okay, if you use each, you have already started traversing the array

    $.each(statuses, function (index, status) {
      console.log(status)
    })

    The output status is each object

    reply
    0
  • 黄舟

    黄舟2017-05-19 10:25:15

    In the console, after clicking on the array, the real-time status is displayed, but when you print, there is only one. Later, the data comes asynchronously and is filled into the array. You will know by outputting the result length in the code

    reply
    0
  • Cancelreply