[英]using typeof to check if a variable is not undefined
why is typeof not checking if a variable is undefined with the below snippets: 为什么typeof不检查以下代码段是否未定义变量:
if(typeof res.data.data[1].name !== undefined){
//the idea is that if code gets here it means it contains some data
.......
}
with the above check I still get this outcome at the if block 通过上面的检查,我仍然在if块得到此结果
TypeError: Cannot read property 'name' of undefined
这可能是因为res.data.data为null,只需添加一个null检查
if(res.data.data && typeof res.data.data[1].name !== undefined){
It is happening because res.data.data[1]
is undefined itself. 这是因为
res.data.data[1]
本身未定义。 I'd suggest expand your condition to something like: 我建议将您的病情扩大至:
const { data = [] } = res.data;
if (data[1] && typeof data[1].name !== 'undefined') {
// Do somehing
}
Also your check is incorrect as you are comparing typeof result with undefined
while it returns a string, in this case 'undefined'
另外,您的检查是不正确的,因为您正在比较typeof结果与
undefined
同时它返回字符串,在这种情况下为'undefined'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.