2016-09-26 42 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

創新的答案,並節省了很多線!非常感謝! –

相關問題