Search code examples
javascriptarraysindexingruntime-error

How to check if index exists in multidimensional array?


I have a for loop for an array where the element may or may not exist:

for (var i = 0; i < array[1][1].length; i++) {
    x[array[1][1][i][1]] =
      array[1][1][i][4][0][4][0][2][0];
}

However, if the element does not exist, it will throw an "Uncaught TypeError: Cannot read properties of null (reading .)" Due to this, I must use an if statement,

for (var i = 0; i < array[1][1].length; i++) {
    if(array[1][1][i][4][0][4][0][2][0]){  
        x[array[1][1][i][1]] =
          array[1][1][i][4][0][4][0][2][0];
    }
}

Unfortunately, this still throws the error if it does not exist because it is being referenced in the if statement. Is there any way around this?


Solution

  • You can use optional chaining. For example,

    for (var i = 0; i < array[1][1].length; i++) {
        if(array?.[1]?.[1]?.[I]?.[4]?.[0]?.[4]?.[0]?.[2]?.[0]){  
            x[array[1][1][i][1]] =
              array[1][1][i][4][0][4][0][2][0];
        }
    }
    

    Edit: My apologies for not adding this earlier, but credit to @Emiel Zuurbier for the idea of optional chaining.