【发布时间】:2020-03-26 08:00:17
【问题描述】:
我想检查一个对象是否未定义
this.state.data.value[0].name
我尝试了以下 这些会说 Type error this.state.data.value is undefined in the console。
if(typeof this.data.value[0].name=== "undefined"){
//do something
}
if(this.data.value[0].name == undefined){
//do something
}
if(!!this.data.value[0].name){
//do something
}
if(!this.data.value[0].name){
//do something
}
if(this.data){
if(this.data.value){ // It says type error, this.state.value is undefined in the console.
}
}
如何检查对象 this.state.value[0].name 是否未定义?
我试过了
if (typeof (this.data) !== undefined) {
debugger;
if (typeof (this.data.value) !== undefined) {
debugger;
if (typeof (this.data.value[0].name != undefined)) {//cannot read value [0]
debugger;
}
}
}
我的解决方案,感谢pranav-c-balan
if (this.data && this.data.value && this.data.value[0] && this.data.value[0].name) {
return true;
} else {
document.getElementById("myDIV").innerHTML =
"<b>Custom Error Text</b>";
return false;
}
一个有效的例子
let data={};
data.value=[{name:123}];
function checkValue(){
if(data && data.value && data.value[0] && data.value[0].name){
return true;
}else{
return false;
}
}
let correct=checkValue();
if(correct){
console.log("This is valid, data.value[0].name Exist");
}else{
console.log("This is invalid,data.value[0].name do not Exist");
}
function checkValue2(){
if(data && data.value && data.value[0] && data.value[0].names){
return true;
}else{
return false;
}
}
let correct2=checkValue2();
if(correct2){
console.log("This is valid, data.value[0].names Exist");
}else{
console.log("This is invalid,data.value[0].names do not Exist");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.0/react-dom.min.js"></script>
【问题讨论】:
-
this.state.data.value && -
@VLAZ,不,因为您向它展示了一层对象的示例,但我想检查一个嵌套对象 this.state.value[0].name 它可能是 this.state。值存在但没有 .name 属性,那么我想要这个 if 语句来捕捉它并做一些事情。尽管如此,当我写 this.state.value 时,控制台已经抛出一个错误,说 this.state.value 是未定义的
-
@PranavCBalan 我试过 if (!this.data && !this.data.value && !this.data.value[0] && !this.data.value[0].name) { / / if 语句没有被评估
-
@RandomI.T
!this.data表示只有falsy才会进入,所以如果this.data存在则跳过。删除 NOT。 -
@PranavCBalan,我喜欢你的想法,它简单而且有效!!!!
标签: javascript object undefined