[英]JQuery undefined object attribute still causes error even when not called
I'm iterating through an api object and certain results do not have a specific attribute. 我正在遍历api对象,某些结果没有特定的属性。 I used this to make a placeholder if the attribute was missing: 如果缺少属性,我就用它做一个占位符:
if (data.track[i].image == undefined) {
urlstring = "path/to/image";
} else {
urlstring = data.track[i].image[4][0];
}
Unfortunately, I still get the error Uncaught TypeError: Cannot read property '0' of undefined
, even though the else clause shouldn't trigger if the attribute is undefined. 不幸的是,我仍然收到错误Uncaught TypeError: Cannot read property '0' of undefined
,即使在属性未定义的情况下else子句也不会触发。
Your problem is that data.track[i].image[4]
is undefined
while your code seems to expect an array. 您的问题是data.track[i].image[4]
undefined
而您的代码似乎期望使用数组。
You might use 你可能会用
if (data.track[i].image && data.track[i].image[4]) {
urlstring = data.track[i].image[4][0];
} else {
urlstring = "path/to/image";
}
Note: I assumed the mix between data.track[i]
and data.toptracks.track[i]
is an artefact of the question. 注意:我假设data.track[i]
和data.toptracks.track[i]
之间的混合是问题的data.track[i]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.