2011-04-29 96 views
3

我的IVR應用程序以JS對象和數組的形式接收業務數據。JavaScript:檢查對象字段是否未定義而未檢查對象是否未定義

customerData.customerList[customerIndex].customerName 

現在,在某些情況下,客戶名稱是不確定的,因爲整個對象是不確定的:例如,如下我們的一個客戶的名字被訪問。眼下,爲了趕上這一點,我有一個檢查被不確定的每個級別一些的嵌套邏輯,最後檢查前最後:

if (typeof customerData != 'undefined' && 
    typeof customerData.customerList && 
    typeof customerData.customerList[customerIndex] != 'undefined' && 
    typeof customerData.customerList[customerIndex].customerName != 'undefined') 
{ 
    //do something awesome with customer name, here 
} 

有沒有做到這一點更容易(清潔?)的方式,而不必檢查對象上的每個字段?

謝謝。

回答

6

您需要編寫第一個typeof以確保customerData已被聲明。在此之後,你可以跳過測試未定義高達任何級別您希望

((customerData || {}).customerList || [])[customerIndex] !== undefined 
+1

如果還沒有用'var'聲明''customerData',你仍然需要'typeof'檢查。 – 2011-04-29 18:37:34

+0

你是對的,但之後可以避免測試'undefined'到邏輯的任何級別 - 或者 – Imran 2011-04-29 18:40:27

+0

你的方法很聰明,它讓我想起了我曾經在遍歷由Web服務返回的XML文檔時使用的一種方法:-) +1。 – 2011-04-29 18:42:14

1

我知道這個作品,但冒昧猜測會有一些反對意見......我很想聽聽:

var customerName = function(){ 
    try{ return customerData.customerList[customerIndex].customerName; } 
    catch(e){ return null; } 
}; 
if (customerName) { 
    ... 
} 
+0

Try-catch塊對於瀏覽器難以優化。要了解更多:https://github.com/petkaantonov/bluebird/wiki/Optimization-killers – Venar303 2015-03-09 19:59:34