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;
}
Ajax是异步过程,回调函数是在数据取回之后才执行的操作
而你的results.push(result),在数据没有取回的时候应该已经push进去了
所以你查看的时候是还没push进去数据的数组,
要等数据加载完你再console才能看得到数据
前面的Ajax嵌套也是同理
undefined也可以存进数组里,并且也有长度。
老哥…截图求截全,
好了,你用了each 那就已经开始遍历数组了
输出的status 就是各个object
控制台中,点击数组后显示的是实时的状态,而你打印时只有一个,后面异步来了数据填充进了数组。你在代码里输出result长度就知道