检查json中是否存在元素

osh*_*nen 10 javascript jquery json jsonp

使用以下Feed:

http://api.twitter.com/1/statuses/user_timeline.json?screen_name=microsoft&include_rts=1&count=10

我成功地遍历了这个以获取我想要在我的html页面上显示的细节.

但是,我需要检查是否retweeted_status.user.profile_image_url存在,我不知道该怎么做?

目前我正在遍历datajquery-ajax返回的数据:

data[i].retweeted_status.user.profile_image_url

如果data[i].retweeted_status.user.profile_image_url不存在,它不返回null或undefined,我只是得到以下错误:

cannot read property 'user' of undefined

Lia*_*ley 28

该错误消息表明您的data [i]或者您的retweeted_status未定义,这意味着您获取json的调用很可能失败.当从Twitter返回数据时,它将会有一个配置文件图像网址,因为它们显示了那些没有上传的人的蛋形图像.你应该把它放在你的for循环之前:

if (typeof(retweeted_status) != "undefined")
{
//code for what to do with json here
}
Run Code Online (Sandbox Code Playgroud)


z_i*_*inx 10

我认为这是一个很好的答案:

if('key' in myObj)
Run Code Online (Sandbox Code Playgroud)