2014-04-15 45 views
1

在javascript中我們有一個很大的分層對象(最糟糕的傳統設計)。我面臨的問題是,每當我想要訪問對象結構中的深層元素時,都需要執行空檢查列表。Null檢查Javascript中的大型分層對象

說我有一個包含客戶列表的銀行對象,我想第一個客戶的地址,

if(bank != null || 
bank.customerlist != null || 
bank.customerlist.customer[0] != null || 
bank.customerlist.customer[0].address != null) 
{ 

transactionAddress = bank.customerlist.customer[0].address; 
} 

這只是一個小例子,我不能相信這麼多的空支票需要 只是爲了訪問一個值。

有沒有更好的解決辦法呢?

+1

將其封裝在'嘗試{...}趕上(E){...}' – phylax

+0

看來這個問題是重複的。我的答案與另一個線程中的[@ kennebec's](http://stackoverflow.com/a/2631521/1529630)幾乎相同;我沒有模仿他,強硬。 – Oriol

回答

1

你可以創建自己的訪問器功能:

function access(obj, path) { 
    var arr = path.split('/'); 
    while(obj && arr.length) 
     obj = obj[arr.shift()]; 
    return obj; 
} 

而且使用這樣的:

var bank = { 
    customerlist: {customer: [{address: 'foo'}]} 
} 
access(bank, 'customerlist/customer/0/address'); // 'foo' 
access(bank, 'bar/foo/foobar');     // undefined (no error) 

而且考慮使用...

function access(obj, path) { 
    var arr = path.split('/'); 
    while(obj!=null && arr.length) 
     obj = obj[arr.shift()]; 
    return obj; 
} 

...如果你想使用access與非對象,例如,你想access('', 'length')返回0


解釋,

function access(obj, path) { 
    var arr = path.split('/'); 
    while (
     obj /* To avoid `null` and `undefined`. Also consider `obj != null` */ 
     && /* Logical AND */ 
     arr.length /* Check that `arr` still has elements */ 
    ) { 
     obj = obj[arr.shift()]; /* `arr.shift()` extracts the first 
            element is `arr` */ 
    } 
    return obj; 
} 
+0

這看起來像一個不錯的選擇,即時通訊有點新的JavaScript,你能告訴我什麼是這樣做,而條件:while(obj && void 0!==(prop = arr.shift()))? – DntFrgtDSemiCln

+0

@DntFrgtDSemiCln它檢查'obj'是否真的(避免'null'和'undefined'),它將'arr'的第一個元素提取到'prop',並檢查'​​prop'不是'undefined'(I使用'void 0'是因爲'undefined'可能已被改變)。 – Oriol

+0

非常感謝您的解釋! @Oriol,你認爲try catch塊也會有幫助嗎? – DntFrgtDSemiCln

2

您可以使用try catch塊:

try { 
    var transactionAddress = bank.customerlist.customer[0].address; 
} catch(e) { 
    // handle the error here 
}