简体   繁体   中英

Checking if a variable is undefined returns the variable is undefined

I have a statement in my code:

if(!(typeof options.duration[i] === 'undefined'))

I have written it correctly, seems that there is no mistake but the console is throwing error that:

TypeError: options.duration is undefined

It should not show this error.It does not make any sense.

The variable options.duration is undefined, so accessing item i from it will result in this error. Perhaps try:

if(typeof options.duration !== 'undefined')

Or if you need to check both options.duration and options.duration[i] , try

if(typeof options.duration !== 'undefined' &&
   typeof options.duration[i] !== 'undefined')

为了使测试成功,还必须定义数组options.duration本身。

You get that error because the duration property doesn't exist.

Check if the property exists before you try to check items in it:

if('duration' in options && typeof options.duration[i] !== 'undefined')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM