[英]Checking if a variable is undefined returns the variable is undefined
我的代碼中有一條語句:
if(!(typeof options.duration[i] === 'undefined'))
我已經正確地編寫了它,似乎沒有錯誤,但是控制台拋出了以下錯誤:
TypeError: options.duration is undefined
它不應顯示此錯誤,這沒有任何意義。
變量options.duration
是未定義的,因此從中訪問項目i
將導致此錯誤。 也許嘗試:
if(typeof options.duration !== 'undefined')
或者,如果您需要同時檢查options.duration
和options.duration[i]
,請嘗試
if(typeof options.duration !== 'undefined' &&
typeof options.duration[i] !== 'undefined')
為了使測試成功,還必須定義數組options.duration
本身。
您收到該錯誤,因為duration
屬性不存在。
在嘗試檢查屬性之前,請檢查該屬性是否存在:
if('duration' in options && typeof options.duration[i] !== 'undefined')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.