最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript 4D arrays - Stack Overflow

programmeradmin2浏览0评论

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 arr[3][2][23][12] = "awesome";

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 arr[3][2][23][12] = "awesome";

Share Improve this question asked May 19, 2011 at 2:22 trusktrtrusktr 45.5k58 gold badges209 silver badges287 bronze badges 1
  • possible duplicate of Is there a more concise way to initialize empty multidimensional arrays? – Anderson Green Commented Jul 21, 2013 at 21:18
Add a comment  | 

8 Answers 8

Reset to default 8
function make(dim, lvl, arr) {
  if (lvl === 1) return [];
  if (!lvl) lvl = dim;
  if (!arr) arr = [];
  for (var i = 0, l = dim; i < l; i += 1) {
    arr[i] = make(dim, lvl - 1, arr[i]);
  }
  return arr;
}

var myMultiArray = make(4);

Update: you can specify how deep a level should be in the first parameter, and how many levels in the second. e.g.:

var myMultiArray = make(64, 4);

This will allow you to set and get in this format:

myMultiArray[X][X][X][X] = ....

But X must always be less than 64. You cannot set myMultiArray[X][70][X][X] for example, because myMultiArray[X][70] has not yet been defined

Note- running make(64, 4) is awfully slow - you are creating 64 ^ 4 empty array elements (i.e. 16,777,216).

Update 2: you can get away with the last value as any number or string. Ie. myMultiArray[X][X][X][Y] where X < 64 and Y can be anything.

The algorithm has been optimised as well, give it another go.

Quick and dirty:

var arr = [[[[[]]]]];

Check it out http://jsfiddle.net/MJg9Y/

Note: You will still need to initialize each dimension. The above creates the foundation for a 4 dimension array at arr[0].

Here's a simple recursive solution. The real brains is the mdim function. It just calls itself if the depth isn't 1, and when it gets there just returns an empty array.

Since it seems like you might want to use this for a lot of things, I've wrapped it in a prototype off of Array so that you can use it on your arrays automatically (convenience/maintainability tradeoff). If you prefer, grab the mdim function out of the closure and it should work just fine.

There's a simple test case at the end so you can see how to use it. Good luck! :)

//adds a multidimensional array of specified depth to a given array
//I prototyped it off of array for convenience, but you could take 
//just the mdim function
Array.prototype.pushDeepArr = function( depth ){
    var arr = (mdim = function( depth ){
        if( depth-- > 1 ){
            return [ mdim( depth ) ];
        } else {
            return [];
        }
    })(depth);
    this.push(arr);
};

//example: create an array, add two multidimensional arrays
//one of depth 1 and one of depth 5
x = [];
x.pushDeepArr(1);
x.pushDeepArr(5);

Just set each value in an existing array equal to a new array, with however many elements you need.

See this tutorial for some good examples. You can do this with any number of dimensions.

var myArray = new Array(3);

for (var i = 0; i < 3; i++) {
    myArray[i] = new Array(3);
    for (var j = 0; j < 3; j++) {
        myArray[i][j] = '';
    }
}

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

Fwiw, I posted an object with a three dimensional array here. In that example,

objTeams.aaastrTeamsByLeagueCityYear["NFL"]["Detroit"][2012] == "Lions".

Very simple function, generate an array with any number of dimensions. Specify length of each dimension and the content which for me is '' usually

function arrayGen(content,dims,dim1Len,dim2Len,dim3Len...) {
  var args = arguments;
  function loop(array,dim) {
    for (var a = 0; a < args[dim + 1]; a++) {
      if (dims > dim) {
        array[a] = loop([],dim + 1);
      } else if (dims == dim) {
        array[a] = content;
      }
    }
    return array;
  }
  var thisArray = [];
  thisArray = loop(thisArray,1);
  return thisArray;
};

I use this function very often, it saves a lot of time

Use the following function to create and initialize Array of any dimension

function ArrayND(initVal) 
{
    var args = arguments;
    var dims=arguments.length-1
    function ArrayCreate(cArr,dim)
    {
        if(dim<dims)
        {
            for(var i=0;i<args[1 + dim];i++)
            {
                if(dim==dims-1) cArr[i]=initVal
                else    cArr[i]=ArrayCreate([],dim+1)
            }
            return cArr
        }
    }
    return ArrayCreate([],0)
}

For e.g to create an array of 2 rows and 3 columns use it like the following

var a=ArrayND("Hello",2,3)

This will create the require array and initialize all values with "Hello"

Similarly to create 4 dimensional array use it like

var a=ArrayND("Hello",2,3,4,5)
发布评论

评论列表(0)

  1. 暂无评论