6

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
}
2
  • 2
    if (arr && arr[d1] && arr[d1][d2]) { .. } - Arrays are never falsy, so this works. Commented Jul 4, 2012 at 16:47
  • Your code won't work when arr = null. Commented Jul 4, 2012 at 18:25

2 Answers 2

3

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));
Sign up to request clarification or add additional context in comments.

Comments

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.