Create new empty N-dimmensional array

Sunday, 3 August 2008 17:34 by MartinKirk

when creating an array using the constructor, there are reasons to be aware: 

  • new Array(5) creates an 1 dimmensional array of length 5, with undefined in all 5 slots
  • new Array(2,5) creates an array of length 2, like this [2,5] instead of a 2 dimmensional array

if you are used to array initializers from VBscript, C / C++ or C# you may sometimes be mistaken by the output. therefore i've prototyped a new initializer for creating empty arrays:

Array.prototype.NewEmpty = function(arr)
{
    var a = [];
    if(arr.length > 1){
        for(var i=0; i<arr[0]; i++){
            a[i] = [].NewEmpty(arr.slice(1));
        }
    }else{
        for(var i=0; i<arr[0]; i++){
            a[i] = undefined;
        }
    }
    return a;
};
var a = [].NewEmpty([3,3,3]);

//--------------
// this is an alternative:

Array.prototype.NewEmpty = function()
{
    var a = [], i;
   
    if(this.length > 1){
        for(i=0; i<this[0]; i++){
            a[i] = this.slice(1).NewEmpty();
        }
    }else{
        for(i=0; i<this[0]; i++){
            a[i] = undefined;
        }
    }
    return a;
};
var a = [3,3,3].NewEmpty(); 

Comments are closed