Javascript 数组在JSON请求之外消失

Javascript 数组在JSON请求之外消失,javascript,jquery,arrays,json,object,Javascript,Jquery,Arrays,Json,Object,我正在尝试使用YouTube视频的各种属性设置一个数组(您可能认为这有点多余,但我计划在将来添加其他源)。我可以将这些值添加到JSON请求中的数组中,但一旦我退出,它们就会消失。有什么想法吗 var socialPosts = new Array(); $.getJSON('https://gdata.youtube.com/feeds/api/videos?author=google&max-results=5&v=2&alt=jsonc&orderby=pu

我正在尝试使用YouTube视频的各种属性设置一个数组(您可能认为这有点多余,但我计划在将来添加其他源)。我可以将这些值添加到JSON请求中的数组中,但一旦我退出,它们就会消失。有什么想法吗

var socialPosts = new Array(); 
$.getJSON('https://gdata.youtube.com/feeds/api/videos?author=google&max-results=5&v=2&alt=jsonc&orderby=published', function(data) {
    for(var i=0; i<data.data.items.length; i++) { //for each YouTube video in the request
        socialPosts[i]={date:Date.parse(data.data.items[i].uploaded), title:data.data.items[i].title,source:"YouTube", thumbnail:data.data.items[i].thumbnail.hqDefault, url:'http://www.youtube.com/watch?v=' + data.data.items[i].id}; //Add values of YouTube video to array
    }
    console.log(socialPosts[0].date); //This returns the correct data
});
console.log(socialPosts[0].date); //This returns with undefined
var socialPosts=new Array();
$.getJSON('https://gdata.youtube.com/feeds/api/videos?author=google&max-结果=5&v=2&alt=jsonc&orderby=published',函数(数据){

对于(var i=0;i您正在尝试访问尚未返回的Ajax
asyn
调用的结果。您需要在回调函数中使用结果,或者将结果传递给某个函数

var socialPosts=new Array();
$.getJSON('https://gdata.youtube.com/feeds/api/videos?author=google&max-结果=5&v=2&alt=jsonc&orderby=published',函数(数据){

对于(var i=0;i,因为这是一个Ajax函数,它是异步的,这意味着闭包外的代码在调用完成之前执行

了解异步请求。您正在使用
$.getJSON
检索异步数据,并且您只能在回调函数中处理数据。
var socialPosts = new Array(); 
$.getJSON('https://gdata.youtube.com/feeds/api/videos?author=google&max-results=5&v=2&alt=jsonc&orderby=published', function(data) {
    for(var i=0; i<data.data.items.length; i++) { //for each YouTube video in the request
        socialPosts[i]={date:Date.parse(data.data.items[i].uploaded), title:data.data.items[i].title,source:"YouTube", thumbnail:data.data.items[i].thumbnail.hqDefault, url:'http://www.youtube.com/watch?v=' + data.data.items[i].id}; //Add values of YouTube video to array
    }
    console.log(socialPosts[0].date); //This returns the correct data
    somefun(socialPosts[0].date); 
});