2010-08-24 51 views
3

當運行:的Javascript多維isset()函數

if (data.custaccount.webaddress) { 
    alert('found it'); 
} 

我得到

data.custaccount is undefined 

我可以避開它的唯一方法似乎是與多個國際單項體育聯合會,像這樣的錯誤:

if (undefined != data && undefined != data.custaccount && undefined != data.custaccount.webaddress) { 
    alert('found it'); 
} 

有什麼辦法可以做得更簡單嗎?

在php中,我們通常會使用isset(data.custaccount.webaddress)並且工作得很好。有沒有在JavaScript(或jQuery)的等價物?

我們已經使用了try/catch,但發現這會顯着降低腳本的性能。

我見過別人問上http://verens.com/2005/07/25/isset-for-javascript/沒有任何成功類似的東西,但我希望計算器會做它節省了一天:)

感謝的正常工作!

賈斯汀

回答

2

當然,你需要檢查是否data定義,訪問data.custaccount.webaddress之前。

你可以寫檢查更縮短喜歡

if(data && data.custaccount && data.custaccount.webaddress){ 
} 

您需要檢查的!

你說得對,使用try/catch將是不好的做法。查找對象的另一種方式可能是通過使用in運營商像

if('custaccount' in data && 'webaddress' in data.custaccount){ 
} 
+2

第一種方法似乎是顯而易見的,但沒有充分發揮作用:如果'data.custaccount.webaddress'返回falsy值('FALSE', '0',''「'等),它沒有做它打算做的事情。 – 2010-08-24 12:45:48