Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
a[0][0]='1';
a[0][1]='2';
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 a[0][x]. For example, when I ask for a[0][2] (which is not defined), it shows the first alert. However, when I ask for a[1][0], I get:

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

How can I solve this problem?

Thanks

like image 334
Robert Smith Avatar asked Feb 27 '11 16:02

Robert Smith


1 Answers

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)
like image 64
Caspar Kleijne Avatar answered Sep 29 '22 21:09

Caspar Kleijne