使用typeof检查变量是否未定义

时间:2018-10-13 19:21:03

标签: javascript angularjs

为什么typeof不检查以下代码段是否未定义变量:

 if(typeof res.data.data[1].name !== undefined){
//the idea is that if code gets here it means it contains some data
    .......
    }

通过上面的检查,我仍然可以在if块上获得此结果

TypeError: Cannot read property 'name' of undefined

2 个答案:

答案 0 :(得分:1)

这可能是因为res.data.data为null,只需添加一个null检查

if(res.data.data && typeof res.data.data[1].name !== undefined){

答案 1 :(得分:0)

之所以发生,是因为res.data.data[1]本身是未定义的。我建议将您的病情扩大至:

const { data = [] } = res.data;
if (data[1] && typeof data[1].name !== 'undefined') {
  // Do somehing
}

您的检查也不正确,因为您正在将typeof结果与undefined进行比较,同时返回一个字符串,在这种情况下为'undefined'

相关问题