2012-01-18 9 views
2

をチェックし、私は私が正しくundefinedをチェックするための推奨in this questionに従ったと思った:「未定義」これはJavaScriptが悪いのかわからないが

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

しかし、上記のコードは、このエラーが発生します。

Uncaught TypeError: Cannot read property 'city' of undefined 

このチェックを行う正しい方法は?

答えて

2

チェック:

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

undefinedを記録することがありますが、エラーにはなりません。 cityでない場合は、undefinedでログに記録する場合は、&& typeof session.location.address.city != "undefined"を追加してください。この場合、cityに空の文字列またはnullが含まれていると、false(つまり、「偽」)と評価されるため、typeofを使用します。もちろん、値がある場合は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); 
関連する問題