Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a 2D array with specific length and width [closed]

*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:

[][][]
[][][]
[][][]
[][][]
like image 733
lawx Avatar asked Dec 12 '22 19:12

lawx


2 Answers

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;
}
like image 89
Kyle Avatar answered Apr 06 '23 01:04

Kyle


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

like image 26
Moritz Roessler Avatar answered Apr 06 '23 00:04

Moritz Roessler