I need to make a recursive multidimensional array in javascript. I have made a function that clones an array, and I thought what the function of the matrix would be, but I do not know what I'm doing wrong.
I want, for example, matrix([2,3,4])
to return this to me:
[[[0,1,2,3]], [0,1,2,3], [0,1,2,3]], [[0,1,2,3], [0, 1,2,3], [0,1,2,3]]]
This means that the length of the array entered is the number of dimensions, and the numbers are the value of the dimensions, having a 3D matrix of 2x3x4 (height, width and height).
This is my code:
function copiarArray(A)
{
var B=[]
for(var i=0;i<A.length;i++)
{
B[i]=A[i]
}
return B
}
function matriz(dims)
{
var I=dims[0]
dims.shift()
var A=[]
A.length=I
for(var i=0;i<I;i++)
{
var dims2=copiarArray(dims)
A[i]=matriz(dims)
dims=dims2
}
return A
}
Currently the error he gives me is:
Uncaught RangeError: Invalid array length (...)
Edit:
If possible, I would like matriz(dims)
to only receive one argument, that is, not allow more than one ... Otherwise, instead of [0,1,2,3]
, let all values be in 0
, in this way, [0,0,0,0]
.