2016-05-31 74 views
0

如果響應沒有msgs[0]屬性,則以下測試會生成錯誤。只有在存在屬性時才測試屬性?

if response.msgs[0] === "published" { ... } 

的錯誤是:

Uncaught TypeError: Cannot read property '0' of undefined 

我怎麼可以重寫測試產生一個錯誤?如果沒有msgs[0]屬性,我希望測試評估爲false

+0

'response.hasOwnProperty( '封郵件')' – Rayon

+0

@Rayon - 將返回TRUE;即使值爲'undefined',在哪個情況下訪問'[0]'仍然會拋出問題中引用的錯誤。 – Quentin

+0

@Quentin,真的!只有在密鑰不存在的情況下才爲False :) – Rayon

回答

7

響應不具有封郵件[0]屬性

這是不正確。它會拋出一個錯誤,因爲它沒有msgs屬性,而不是因爲它上面沒有0屬性。

在測試0是什麼之前,您需要測試msgs是否存在。

if (response.msgs && response.msgs[0] === "published") { ... } 
+0

即使定義了msgs,如果不存在'[0]','msgs [0]'仍然會產生一個錯誤('意外的輸入結束') 。 – Eric

+1

@ErikKralj - 不,它不會:http://jsbin.com/zuhose/2/edit?js,console – Quentin

+0

你是對的,它不會,我的不好。 – Eric

3

測試是否response.msgs首先定義:

if response.msgs && response.msgs[0] === "published" { ... }