不确定是什么';这个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);