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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With