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
}
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
}
Share
Improve this question
asked Jul 4, 2012 at 16:44
AlexAlex
711 silver badge3 bronze badges
2
-
2
if (arr && arr[d1] && arr[d1][d2]) { .. }
- Arrays are never falsy, so this works. – Rob W Commented Jul 4, 2012 at 16:47 -
Your code won't work when
arr = null
. – Bergi Commented Jul 4, 2012 at 18:25
2 Answers
Reset to default 3This 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/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
}