您好,我正在查询 Amazon API,但有时商品没有图像。我正在尝试解决此问题,但仍然收到错误:TypeError:无法读取未定义的属性“0”
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 - 这将解释对象属性根本不存在?或者谁能给出如何解决的建议?
谢谢
最佳答案
typeof
总是返回一个字符串,所以它是
if ( typeof something_to_check !== 'undefined' )
如果您检查实际的undefined
,它会失败,因为undefined !== "undefined"
至于错误,这意味着您正在尝试访问未定义的内容的第一个索引 ([0]
)
result.ItemSearchResponse.Items
或
result.ItemSearchResponse.Items[0].Item
或
result.ItemSearchResponse.Items[0].Item[i].SmallImage
或
result.ItemSearchResponse.Items[0].Item[i].SmallImage[0].URL
如果你不知道哪一个失败了,你就必须检查每一个
if ( result.ItemSearchResponse.Items &&
result.ItemSearchResponse.Items[0].Item &&
result.ItemSearchResponse.Items[0].Item[i].SmallImage &&
result.ItemSearchResponse.Items[0].Item[i].SmallImage[0].URL
) {
// use
var img = result.ItemSearchResponse.Items[0].Item[i].SmallImage[0].URL[0]
}
如果索引可能是错误的,或者不是数组等,您也必须检查这一点。
关于javascript - 在 JavaScript 中使用 typeof 仍然会导致 undefined object 的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39712463/