2010-08-24 55 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