如果響應沒有msgs[0]
屬性,則以下測試會生成錯誤。只有在存在屬性時才測試屬性?
if response.msgs[0] === "published" { ... }
的錯誤是:
Uncaught TypeError: Cannot read property '0' of undefined
我怎麼可以重寫測試產生一個錯誤?如果沒有msgs[0]
屬性,我希望測試評估爲false
。
如果響應沒有msgs[0]
屬性,則以下測試會生成錯誤。只有在存在屬性時才測試屬性?
if response.msgs[0] === "published" { ... }
的錯誤是:
Uncaught TypeError: Cannot read property '0' of undefined
我怎麼可以重寫測試產生一個錯誤?如果沒有msgs[0]
屬性,我希望測試評估爲false
。
響應不具有封郵件[0]屬性
這是不正確。它會拋出一個錯誤,因爲它沒有msgs
屬性,而不是因爲它上面沒有0
屬性。
在測試0
是什麼之前,您需要測試msgs
是否存在。
if (response.msgs && response.msgs[0] === "published") { ... }
測試是否response.msgs
首先定義:
if response.msgs && response.msgs[0] === "published" { ... }
'response.hasOwnProperty( '封郵件')' – Rayon
@Rayon - 將返回TRUE;即使值爲'undefined',在哪個情況下訪問'[0]'仍然會拋出問題中引用的錯誤。 – Quentin
@Quentin,真的!只有在密鑰不存在的情況下才爲False :) – Rayon