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

时间:2014-03-13 16:25:41

标签: javascript

我的代码中有一条声明:

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

我写得正确,似乎没有错,但是控制台抛出错误:

TypeError: options.duration is undefined

它不应该显示此错误。它没有任何意义。

3 个答案:

答案 0 :(得分:3)

变量options.duration未定义,因此从中访问项i将导致此错误。也许试试:

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

或者,如果您需要同时检查options.durationoptions.duration[i],请尝试

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

您收到该错误,因为duration属性不存在。

在尝试检查其中的项目之前,请检查该属性是否存在:

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