Javascript 4D arrays

前端 未结 8 709
一生所求
一生所求 2020-12-06 03:39

Anyone have a function to create 4D arrays (or any number of dimensions for that matter)?

I\'d like to call the function, then after that I can do something like

8条回答
  •  甜味超标
    2020-12-06 04:10

    Update Corrected some issues with the previous function; this seems to do the trick:

    function multidimensionalArray(){
        var args = Array.prototype.slice.call(arguments);
    
        function helper(arr){
            if(arr.length <=0){
                return;
            }
            else if(arr.length == 1){
                return new Array(arr[0]);
            }
    
            var currArray = new Array(arr[0]);
            var newArgs = arr.slice(1, arr.length);
            for(var i = 0; i < currArray.length; i++){
                currArray[i] = helper(newArgs);
            }
            return currArray;
        }
    
        return helper(args);
    }
    

    Usage

    var a = multidimensionalArray(2,3,4,5);
    
    console.log(a); //prints the multidimensional array
    console.log(a.length); //prints 2
    console.log(a[0].length); //prints 3
    console.log(a[0][0].length); //prints 4
    console.log(a[0][0][0].length); //prints 5
    

提交回复
热议问题