在JavaScript中使用typeof仍然会导致未定义对象出错
大家好,我正在查询AmazonAPI,不时有一个项目没有图像。我正在尝试对此进行解释,但仍然出现错误:TypeError:无法读取未定义的属性“0”在JavaScript中使用typeof仍然会导致未定义对象出错,javascript,jquery,amazon-web-services,typeof,Javascript,Jquery,Amazon Web Services,Typeof,大家好,我正在查询AmazonAPI,不时有一个项目没有图像。我正在尝试对此进行解释,但仍然出现错误:TypeError:无法读取未定义的属性“0” if (typeof result.ItemSearchResponse.Items[0].Item[i].SmallImage[0].URL[0] !== undefined) { //items['image'][i] = result.ItemSearchResponse.Items[0].Item[i].La
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!==“未定义”
至于错误,这意味着您正试图访问未定义内容的第一个索引([0]
)
result.ItemSearchResponse.Items
或
或
或
如果你不知道哪一个失败了,你必须检查每一个
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]
}
如果索引可能是错误的,或者不是数组等,您也必须检查它。为什么不使用
var arr = results.ItemSearchResponse.Items[0].Item[i].SmallImage || false;
if(arr[0]){
// do some work
}
由于如果任何包含数组不存在或
SmallImage
中不存在图像,则条件失败,这意味着results.ItemSearchResponse.Items
,results.ItemSearchResponse.Items[0]。Item
,results.ItemSearchResponse.Items[0]。Item[i].SmallImage
或结果.ItemSearchResponse.Items[0]。Item[i]。SmallImage[0]。URL
未定义。基本上,您在某个索引中访问的任何内容都可能是未定义的。独立验证它们。您需要检查对象的每个级别,typeof
不处理RHS中的引用错误,typeof foo;//未定义
但foo.bar的类型;//错误
尝试记录每个数组以获取未定义的数组console.log(results.ItemSearchResponse.Items[0]。Item)console.log(results.ItemSearchResponse.Items[0]。Items[0]。console.log(results.ItemSearchResponse.Items[0]。Item[i]。SmallImage[0]。UR五十) 谢谢!是的,我刚检查过,有一个项目缺少URL。我想我应该将此检查添加到所有返回的属性中。window.foo.bar不(可能)返回赋值将抛出的字符串,因此您可能希望将其包含在try块中。创新的答案并节省了大量行!谢谢!
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]
}
var arr = results.ItemSearchResponse.Items[0].Item[i].SmallImage || false;
if(arr[0]){
// do some work
}