*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:
[][][]
[][][]
[][][]
[][][]
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With