I get responses from the server, for example Correct answer

But, sometimes the server returns like Incomplete answer

And when I request for example data.rows[1 (и больше)][1] The console issues this

"Uncaught TypeError: Cannot read property '1' of undefined"

Which is logical, I want to make an exception so that a similar error is processed and data.rows[1 (и больше)][1] assigned zeros

  • 3
    check the length property before accessing, so as not to go beyond - Grundy
  • What if data.rows = null ? - Kernozz
  • 2
    Check for data.rows . - Arnial
  • one
    @Trick, oddly enough, but this case must also be checked. - Grundy

1 answer 1

Checking the existence of properties is done like this:

 if('data' in json) 1 

Arrays should be processed using tools created for this, for example:

 json.data.forEach(e => 1); 

It will not go beyond.


You can, of course, be perverted by connecting generators / iterators (although there is something in arrays anyway), but this is a crap in the code world, you shouldn’t do that.