Reputation: 219
I am trying to search in an array via for loop
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:
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?
Upvotes: 0
Views: 38
Reputation: 2377
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
Upvotes: 2