6

*see the title. I basically need it to create a blank array that can be any dimension like 40x60. Basically maybe something like makeArray(3, 4) makes an array like:

[][][]
[][][]
[][][]
[][][]
lawx
  • 368
  • 1
  • 5
  • 19
  • 1
    JavaScript arrays are not fixed-size, so you can usually get away with not preallocating them. [What have _you_ tried?](http://whathaveyoutried.com) – Matt Ball Dec 10 '12 at 20:08
  • @MattBall I have seen questions like this but it's usually for a making a square array not a specified X and Y dimension. – lawx Dec 10 '12 at 20:15
  • That's pretty much irrelevant. "Square array" is just the special case of rows == columns. – Matt Ball Dec 10 '12 at 20:18

2 Answers2

14

Javascript arrays are dynamic in size. However, if you wish to create an array of a specific size, the Array constructor takes an optional length argument:

function makeArray(d1, d2) {
    var arr = new Array(d1), i, l;
    for(i = 0, l = d2; i < l; i++) {
        arr[i] = new Array(d1);
    }
    return arr;
}

Slightly shorter:

function makeArray(d1, d2) {
    var arr = [];
    for(let i = 0; i < d2; i++) {
        arr.push(new Array(d1));
    }
    return arr;
}

UPDATE

function makeArray(w, h, val) {
    var arr = [];
    for(let i = 0; i < h; i++) {
        arr[i] = [];
        for(let j = 0; j < w; j++) {
            arr[i][j] = val;
        }
    }
    return arr;
}
Kyle
  • 4,421
  • 22
  • 32
2

Well make Array would be a simple function like this

    ​function makeArray(a,b) {
        var arr = new Array(a)
        for(var i = 0;i<a;i++)
            arr[i] = new Array(b)
        return arr
    }
    console.log(makeArray(4,4))

​ But you don't have to define Arrays with functions you can simply do something like

var arr=[]
arr[10] = 10

Which would result in a Array with 10 Elements, 0 - 9 are undefined

But thats enough of an Answer in this case, i tried to point some things out in this question regarding Arrays, if you're interested you can take a look at this question

Community
  • 1
  • 1
Moritz Roessler
  • 8,542
  • 26
  • 51