Javascript multidimensioned isset()
When running:
if (data.custaccount.webaddress) {
alert('found it');
}
I get the error
data.custaccount is undefined
The only way i can get around it seems to be with multiple IFs like so:
if (undefined != 开发者_开发问答data && undefined != data.custaccount && undefined != data.custaccount.webaddress) {
alert('found it');
}
Is there any way i could do this more simply?
In php we'd normally use the isset(data.custaccount.webaddress) and that worked quite well. is there an equivalent in javascript (or jquery)?
We have used try / catch, but found that to slow down performance of the script considerably.
I've seen someone else asking something similar on http://verens.com/2005/07/25/isset-for-javascript/ without any success, but am hoping that stackoverflow will do it's normal job of saving the day :)
Thanks!!!
Justin
Of course you need to check if data
is defined, before accessing data.custaccount.webaddress
.
You can write that check more shorten like
if(data && data.custaccount && data.custaccount.webaddress){
}
You need to check for that!
You're right, using try/catch
would be bad practice. Another way to lookup the object could be by using the in
operator like
if('custaccount' in data && 'webaddress' in data.custaccount){
}
精彩评论