Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Checking whether a multidimensional array is 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
}
like image 743
Alex Avatar asked Jul 04 '12 16:07

Alex


2 Answers

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));
like image 149
techfoobar Avatar answered Oct 17 '22 03:10

techfoobar


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
}
like image 40
Bradmage Avatar answered Oct 17 '22 03:10

Bradmage