[英]JSON Uncaught Type Error
我正在使用instagram API,如果標題不存在或沒有文本,則根本不包含該節點。 因此,我進行了一項檢查,以查看是否存在可以使用標題的標題,但是如果標題存在並且子節點文本不存在,則出現錯誤: Uncaught TypeError: Cannot read property 'text' of null
。
這是我的代碼:
for (p in pictures) {
if (pictures[p].hasOwnProperty('caption')) {
if (pictures[p].caption.text != null) {
captionString = pictures[p].caption.text;
}
}
}
顯然, caption
屬性存在,但在某些情況下似乎為null
,並且當您評估(null).text
,您將得到問題中詳細說明的錯誤。
添加pictures[p].caption &&
來評估if
caption
。
這應該為您工作(請注意,我還將您的兩個if
合並,並且僅對if
進行了所有評估):
for(p in pictures) {
if (pictures[p].hasOwnProperty('caption') && pictures[p].caption && pictures[p].caption.text != null) {
captionString = pictures[p].caption.text;
}
}
您可以嘗試:
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;
}
}
因為caption屬性始終在此處,但如果不可用,則可以為null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.