为什么这个数组在 $.getJSON 之外丢失了它的数据

Why does this Array lose its data outside $.getJSON?

本文关键字:数据 数组 getJSON 为什么      更新时间:2023-09-26

我正在向Instagram发送请求以获取关注者ID,一切正常,直到我想在方法之外使用数组$.getJSON。以下是代码的相关部分:

var allFollowings = [];
 $.getJSON("https://api.instagram.com/v1/users/self/follows?access_token="+$.urlParam('access_token')+"&count="+followingsCount+"&callback=?", function(json) {

   for(var i = 0; i < json.data.length; i++) {
        console.log(json.data[i].id); // this is not empty
        allFollowings[i] = json.data[i].id;
   }
   console.log(allFollowings); // this is also not empty
});
console.log(allFollowings); // this one is empty!!!

显然我做错了什么,这是我第一次遇到这个问题。但是我做错了什么?谢谢。

它实际上不会丢失其数据。发生的情况是,您的 $.getJSON 回调函数在上次console.log(allFollowings);调用后被异步调用。

脚本

末尾的console.loggetJSON调用回调之前执行。这是javascript的异步性质。