简体   繁体   中英

Why is my object property undefined when using it in a if-statement?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM