Javascript - check for multidimensional array undefined

Is there a cleaner / shorter way to check if a multidimensional array is undefined (which avoids undefined error in any dimension) than:

if(arr != undefined && arr[d1] != undefined && arr[d1][d2] != undefined){ // arr[d1][d2] isn't undefined } 

As in the following case, an error is generated if either arr or arr[d1] undefined:

 if(arr[d1][d2] != undefined){ // arr[d1][d2] isn't undefined } 
+6
source share
2 answers

This is disappointing; you cannot check arr [d1] [d2] straight up. But from what I'm compiling, javascript does not support multidimensional arrays.


So the only option you have is what you started 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 } 
+2
source

This will return it in a single check with 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)); 
+2
source

Source: https://habr.com/ru/post/919691/


All Articles