运行时:
if (data.custaccount.webaddress) {
alert('found it');
}
我得到了错误
data.custaccount is undefined
我能绕过它的唯一方法似乎是像这样使用多个 IF:
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/ 上问过类似的问题没有任何成功,但我希望 stackoverflow 能够完成拯救这一天的正常工作 :)
谢谢!!!
贾斯汀
最佳答案
当然,在访问data.custaccount.webaddress
之前,您需要检查是否定义了data
。
你可以把支票写得更短一些
if(data && data.custaccount && data.custaccount.webaddress){
}
你需要检查一下!
你是对的,使用 try/catch
是不好的做法。查找对象的另一种方法是使用 in
运算符,例如
if('custaccount' in data && 'webaddress' in data.custaccount){
}
关于Javascript 多维 isset(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3555516/