[英]Javascript object check if property exists
我有一個名為file的 javascript object ,我正在嘗試檢查此 object 是否包含 file.xhr.response 屬性。 我試過這樣..
if (file.xhr.response) {
console.log(Exists);
} else {
console.log(Missing);
}
這在file.xhr.response存在時有效,但如果不存在,則會引發錯誤...
Uncaught TypeError: Cannot read property 'response' of undefined
我哪里錯了?
您可以使用以下方法檢查對象屬性是否存在:
if (file && file.xhr && file.xhr.response) {
// your logic...
}
代碼示例:
var a = { b: { d: 'd' } }; var resultC = a && ab && abc ? 'Exists' : 'Missing'; console.log('abc', resultC); var resultD = a && ab && abd ? 'Exists' : 'Missing'; console.log('abd', resultD);
使用try / catch語句,如果引發了錯誤,則可以在catch塊中處理它。
您可以使用類似if(typeof file.xhr!="undefined")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.