2016-04-15 36 views
-2

下面是代碼:如何處理JavaScript中未定義的JSON數據?

if (data.result.parameters.q === undefined) { 
    colsole.log('undefined') 
} 
//I also tried 
if (data.result.parameters.q === null) { 
    // colsole.log('undefined') 
// } 

在使用null和undefined,但沒有工作的嘗試。

+1

在控制檯中是否出現錯誤?如果鏈中較早的對象之一爲null,則會引發錯誤。否則,你可以'console.log(data.result.parameters.q)'並測試它所吐出的任何信息 – IrkenInvader

+1

'console.log(data.result.parameters.q)'真的沒有定義? –

+0

什麼是「colsole」? –

回答

1

a === undefined未必檢查undefined,因爲您可以設置var undefined = {}

使用無論是voidtypeof運營商(全等===是沒有必要的):

if(data.result.parameters.q == void(0) || typeof data.result.parameters.q == 'undefined') 
    console.log('data.result.parameters.q is undefined'); 

請問你的數據實際上看?您確定datadata.resultdata.result.parameters已設置?有很多方法來檢查,如hasOwnProperty或一般truthiness

if(data.hasOwnProperty('result') && data.result && data.result.hasOwnProperty('parameters')) 
    // now we can check if there is q in data.result.parameters 

還要注意有一個在你的代碼拼寫錯誤:它console,不colsole

+0

向上投票注意「未定義」在現代瀏覽器中是隻讀的。 – Roberto