不确定是什么';这个JavaScript有什么问题;“未定义”;检查

不确定是什么';这个JavaScript有什么问题;“未定义”;检查,javascript,Javascript,我认为我正确地遵循了检查未定义的建议: if(typeof window.session.location.address.city != "undefined") console.log(window.session.location.address.city); 但上面的代码会生成此错误: Uncaught TypeError: Cannot read property 'city' of undefined 执行此检查的正确方法是什么?地址未定义,因此您无法读取

我认为我正确地遵循了检查
未定义
的建议:

if(typeof window.session.location.address.city != "undefined")       
    console.log(window.session.location.address.city);
但上面的代码会生成此错误:

 Uncaught TypeError: Cannot read property 'city' of undefined
执行此检查的正确方法是什么?

地址未定义,因此您无法读取其属性
城市


您必须首先检查
地址
是否已定义。

检查每个属性是否存在:

if (window.session && session.location && session.location.address)
    console.log(session.location.address.city);
这可能会记录未定义的
,但不会导致错误。如果您只想记录
城市
,如果它不是
未定义的
,只需添加一个
&&typeof session.location.address.city!=“未定义”
。在这种情况下,我们使用
typeof
,因为如果
city
包含空字符串或
null
,它也将计算为
false
(即,它是“false”)。当然,如果您只想在有值的情况下记录
city
,请取消
typeof
,只需检查它的计算结果是否与其他值相同

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