2016-09-26 47 views
0

嗨,我正在查询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 - 会占据对象属性根本不存在?或者任何人都可以提供建议如何解决?

感谢

+3

这意味着'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'。基本上,您在某个索引处访问的任何内容都可能是“未定义”的。独立验证它们。 –

+0

您需要检查Object的每个级别,'typeof'不处理RHS中的引用错误,'typeof foo; // undefined'但是'typeof foo.bar; //错误' –

+0

尝试记录每个数组以获得未定义的数组 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) –

回答

6

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] 
    } 

如果索引可能是错误的,或者不是数组等,你也必须检查。

+0

** typeof window.foo.bar **不(*可能*)返回一个字符串 – JonSG

1

由于如果任何含阵列不存在,或者如果没有图像中存在SmallImage条件失败为什么不使用

var arr = results.ItemSearchResponse.Items[0].Item[i].SmallImage || false; 
if(arr[0]){ 
    // do some work 
} 

+3

该任务将抛出,所以你可能想要附上一个**尝试**块。 – JonSG

+0

@JonSG很好的通话,我没有想到! –

+0

创新的答案,并节省了很多线!非常感谢! –

相关问题