嗨,我正在查询Amazon API,并且每时每刻都有一个项目没有图像。未定义在JavaScript中使用typeof仍然会导致未定义对象的错误
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]);
}
无法读取属性“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'。基本上,您在某个索引处访问的任何内容都可能是“未定义”的。独立验证它们。 –
您需要检查Object的每个级别,'typeof'不处理RHS中的引用错误,'typeof foo; // undefined'但是'typeof foo.bar; //错误' –
尝试记录每个数组以获得未定义的数组 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] .UR L) –