Is there a cleaner/shorter way of checking whether a multidimensional array is undefined (which avoids an undefined error at any dimension) than:
if(arr != undefined && arr[d1] != undefined && arr[d1][d2] != undefined){
// arr[d1][d2] isn't undefined
}
As doing the following will throw an error if either arr
or arr[d1]
is undefined:
if(arr[d1][d2] != undefined){
// arr[d1][d2] isn't undefined
}
This will return it in one check using try/catch.
function isUndefined(_arr, _index1, _index2) {
try { return _arr[_index1][_index2] == undefined; } catch(e) { return true; }
}
Demo: http://jsfiddle.net/r5JtQ/
Usage Example:
var arr1 = [
['A', 'B', 'C'],
['D', 'E', 'F']
];
// should return FALSE
console.log(isUndefined(arr1, 1, 2));
// should return TRUE
console.log(isUndefined(arr1, 0, 5));
// should return TRUE
console.log(isUndefined(arr1, 3, 2));
It's frustrating you can't test for arr[d1][d2] straight up. But from what I gather, javascript doesn't support multidimentional arrays.
So the only option you have is what you sugested with
if(arr != undefined && arr[d1] != undefined && arr[d1][d2] != undefined){
// arr[d1][d2] isn't undefined
}
Or wrapped in a function if you use it regularly.
function isMultiArray(_var, _array) {
var arraystring = _var;
if( _array != undefined )
for(var i=0; i<_array.length; i++)
{
arraystring = arraystring + "[" + _array[i] + "]";
if( eval(arraystring) == undefined ) return false;
}
return true;
}
if( ! isMultiArray(arr, d) ){
// arr[d1][d2] isn't 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