简体   繁体   English

检查变量是否未定义将返回变量未定义

[英]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. 变量options.duration是未定义的,因此从中访问项目i将导致此错误。 Perhaps try: 也许尝试:

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

Or if you need to check both options.duration and options.duration[i] , try 或者,如果您需要同时检查options.durationoptions.duration[i] ,请尝试

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

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

You get that error because the duration property doesn't exist. 您收到该错误,因为duration属性不存在。

Check if the property exists before you try to check items in it: 在尝试检查属性之前,请检查该属性是否存在:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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