[英]Why is my object property undefined when using it in a if-statement?
I am trying to search in an array via for loop我正在尝试通过 for 循环在数组中搜索
let matrix = [];
for(let i=0; i<this.row; i++){
for(let j=0; j<this.column; j++){
if(this.grid[i][j].name != ""){
matrix.push(this.grid[i][j].name);
console.log(matrix);
}
}
but it does not work.但它不起作用。 I get the error that
this.grid[i][j].name
is undefined
although this would work perfectly:我收到
this.grid[i][j].name
undefined
的错误,尽管这可以完美地工作:
let matrix = [];
for(let i=0; i<this.row; i++){
for(let j=0; j<this.column; j++){
if(this.grid[i][j]){
matrix.push(this.grid[i][j].name);
console.log(matrix);
}
}
I ask whether there is an object and if there is one, then push the name property into the variable matrix
and here strangely the property this.grid[i][j].name
is correctly defined but why is it not defined using the property in the if statement?我问是否有一个 object 如果有,然后将 name 属性推入变量
matrix
,奇怪的是属性this.grid[i][j].name
是正确定义的,但为什么没有使用该属性定义在 if 语句中?
please try this approach请尝试这种方法
let matrix = [];
for(let i=0; i<this.row; i++){
for(let j=0; j<this.column; j++){
if(this.grid[i][j] && this.grid[i][j].name){
matrix.push(this.grid[i][j].name);
console.log(matrix);
}
}
this way you can check if this.grid[i][j]
exists then only check for this.grid[i][j].name
这样你可以检查
this.grid[i][j]
是否存在然后只检查this.grid[i][j].name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.