【发布时间】:2016-09-26 21:11:41
【问题描述】:
您好,我正在查询 Amazon API,并且时不时地有一个项目没有图像。我试图解决这个问题,但我仍然收到错误:TypeError: Cannot read property '0' of undefined
if (typeof result.ItemSearchResponse.Items[0].Item[i].SmallImage[0].URL[0] !== undefined) {
//items['image'][i] = result.ItemSearchResponse.Items[0].Item[i].LargeImage[0].URL[0];
console.log(result.ItemSearchResponse.Items[0].Item[i].SmallImage[0].URL[0]);
}
如果我注释掉 if 语句,错误就会消失 - 有没有更好的使用 typeof 的方法 - 这会导致对象属性根本不存在?或者任何人都可以就如何解决提供建议?
谢谢
【问题讨论】:
-
这意味着
results.ItemSearchResponse.Items、results.ItemSearchResponse.Items[0].Item、results.ItemSearchResponse.Items[0].Item[i].SmallImage或results.ItemSearchResponse.Items[0].Item[i].SmallImage[0].URL是undefined。基本上,您在某个索引处访问的任何内容都可能是undefined。独立验证它们。 -
你需要检查Object的每一层,
typeof不处理RHS内的引用错误,typeof foo; // undefined但是typeof foo.bar; // error -
尝试记录每个数组以获取未定义的数组 console.log(results.ItemSearchResponse.Items[0].Item) console.log(results.ItemSearchResponse.Items[0].Item[ i].SmallImage) console.log(results.ItemSearchResponse.Items[0].Item[i].SmallImage[0].URL)
-
谢谢!是的,我刚刚检查过,其中一项缺少 URL。我想我应该将此检查添加到所有返回的属性中
标签: javascript jquery amazon-web-services typeof