2015-01-07 114 views
1

我正在使用instagram API,如果标题不存在或没有文本,它根本不包含节点。所以我包括一个检查,看看是否存在标题工作,但如果标题存在和子节点文本不,然后我得到的错误:Uncaught TypeError: Cannot read property 'text' of nullJSON未捕获类型错误

这是我的代码:

for (p in pictures) { 
    if (pictures[p].hasOwnProperty('caption')) { 
    if (pictures[p].caption.text != null) { 
     captionString = pictures[p].caption.text; 
    } 
    } 
} 
+0

如果标题为空,则没有标题? (但是一个标题属性在这里通知你没有可用的标题),所以只有当标题属性不为空时,你才应该添加一个标题字符串 – Hacketo

回答

2

显然,caption属性存在,但它似乎是null某些情况下,当你评估(null).text,你所得到的错误在你的问题的详细。

pictures[p].caption &&加入以评估您的if

这应该为你工作(注意,我还合并你的两个if S和我做了所有的评价只有一个if):

for(p in pictures) { 
    if (pictures[p].hasOwnProperty('caption') && pictures[p].caption && pictures[p].caption.text != null) { 
    captionString = pictures[p].caption.text; 
    } 
} 
+0

这似乎奏效了。你知道为什么这样做,但不是我做到这一点吗?为什么我在嵌套的if语句检查中遇到错误,而不是这个呢? – shinjuo

+0

请注意,我做了一个小的重构,我合并了你的2个“ifs”,重点是我为'pictures [p] .caption'添加了一个评估,如果这是'null',它将返回false为if语句 – lante

0

你可以只尝试:

if(pictures[p].caption != null){ 
    captionString = pictures[p].caption.text; 
} 

代替

if(pictures[p].hasOwnProperty('caption')){ 
    if(pictures[p].caption.text != null){ 
      captionString = pictures[p].caption.text; 
    } 
} 

因为标题属性总是他如果不可用,则可能为空

+0

我做了,但可以有标题和没有标题文字。不知道为什么但它发生。我检查了JSON输出 – shinjuo