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

Checking if a variable is undefined returns the variable is undefined

本文关键字:变量 未定义 返回 检查 是否      更新时间:2023-09-26

我的代码中有一个语句:

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

我已经写对了,似乎没有错误,但控制台抛出错误:

TypeError: options.duration is undefined

应该不会显示这个错误。没有任何意义

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

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

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

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

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

你得到这个错误是因为duration属性不存在。

检查属性是否存在,然后再尝试检查其中的项:

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