JSON 未捕获的类型错误
JSON Uncaught Type Error
我正在使用 instagram API,如果标题不存在或没有文本,它根本不包含该节点。所以我包括了一个检查,看看是否存在标题,但如果标题存在而 child 节点文本不存在,那么我会得到错误: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;
}
}
因为标题 属性 总是在这里,但如果不可用则可能为空
我正在使用 instagram API,如果标题不存在或没有文本,它根本不包含该节点。所以我包括了一个检查,看看是否存在标题,但如果标题存在而 child 节点文本不存在,那么我会得到错误: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;
}
}
因为标题 属性 总是在这里,但如果不可用则可能为空