数组在JSON请求之外消失 [英] Arrays disappear outside of JSON request

查看:63
本文介绍了数组在JSON请求之外消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am attempting to set up an array with the various properties of a YouTube video (you may be thinking this is somewhat superfluous, however I am planning on adding other sources in the future). I am able to add these values into the array within the JSON request, but once I get out of it, they just disappear. Any ideas?

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

推荐答案

您正尝试访问尚未返回 的Ajax asyn调用的结果.您需要在回调函数中使用result或将结果传递给 some function .

You are trying to access results of Ajax asyn call which are not yet returned. You need to use result in call back function or pass the results to some function.

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); 
});

这篇关于数组在JSON请求之外消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆