简体   繁体   中英

Not sure what's wrong with this JavaScript “undefined” check

I thought I had correctly followed the recommendations in this question for checking undefined :

if(typeof window.session.location.address.city != "undefined")       
    console.log(window.session.location.address.city);

But the code above generates this error:

 Uncaught TypeError: Cannot read property 'city' of undefined

What's the correct way to perform this check?

address is undefined so you can't read its property city

You'll have to check that address is defined first.

Check for the existence of each property:

if (window.session && session.location && session.location.address)
    console.log(session.location.address.city);

That may log undefined , but will not result in an error. If you only want to log city if it is not undefined , just add in a && typeof session.location.address.city != "undefined" . We use typeof in this case because if city contains an empty string or null , it will also evaluate to false (ie, it is "falsey"). Of course, if you only want to log city if it has a value, leave off the typeof and just check to see if it evaluates to true (ie, it is "truthy") the same way as the others.

if(typeof window.session.location.address === 'undefined')
    alert("address is undefined!");
else
    console.log(window.session.location.address.city);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM