2012-01-18 55 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); 
相關問題