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;
}
给我你的怀抱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
迷茫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
黄舟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