2012-01-18 95 views

回答

2

检查每个属性的存在:

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

这可登录undefined,但不会导致错误。如果您只想记录city如果它是而不是undefined,只需添加一个&& typeof session.location.address.city != "undefined"。在这种情况下我们使用typeof,因为如果city包含空字符串或null,它也将评估为false(即它是“falsey”)。当然,如果您只想记录city,如果它有一个值,则请忽略typeof,然后检查它是否以与其他值相同的方式评估为true(即它是“真”)。

4

address不确定,所以你无法读取其属性city

你必须检查address首先被定义。

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