Robert Smith Robert Smith - 4 months ago 24
Javascript Question

Check for existence of key in multidimensional array in javascript

Hopefully an easy question.

Why is that checking for existence of a key in a multidimensional array:

a = new Array(Array());
if(a[1][2] == undefined){
alert("sorry, that key doesn't exist");
} else {alert('good, your key exists');

seems not to be working in general, but it works when I check for a first index (in this case, '0') that is 'defined' by
. For example, when I ask for
(which is not defined), it shows the first alert. However, when I ask for
, I get:

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

How can I solve this problem?



Check first if the first dimension exists then if the key in the second dimension exists

The logic will return false if the first test returns false, and tests the second dimension only if the first one is true.

  if(a[1] == undefined && a[1][2] == undefined)