Multiple variable declaration using loop javascript
I was trying to create an array which contains 3 fixed fields.
So, somet开发者_运维问答hing likevar x0 = new Array(x,y,z);
Now the thing is there can be multiple arrays like x[], which have the different values.
So something like var x1 = new Array(x,y,z); x2 = new Array(x,y,z);
I would be passing values to the variables x,y,z like x0[0] = "test", x0[1] = "another",...
I need to create a variable number of such arrays, so say if i pass a value say 10, it should create 10 different arrays for me. How does one do this, is it allowed to use a loop for creating variables?There is something called as multi dimensional array, but I wasn't sure of how to use it. I tried but apparently it is very different and I did not understand it. Also, I thought of declaring an object, and passing values to it's parameters, and create objects as needed. Is this possible? And which method will be better?
Is there any other way of doing this? maybe something which would be most efficient?
Just create an array of arrays:
var myArrays = [];
for(var i=0;i<something;i++){
myArrays.push([x,y,z]);
}
Then, instead of x0[0]
you would have x[0][0]
.
Note, you shouldn't use new Array
but instead use []
.
Do you mean
var x =[];
x[0]=["x","y","z"];
x[1]=["x","y","z"];
x[2]=["x","y","z"];
or
function addArr(arr,newarr) {
arr[arr.length]=newarr; // or arr.push(newarr);
}
var x =[];
for (var i=0;i<10;i++) {
addArr(x,[i,i+1,i+2]);
}
var n = 100; // number of x-arrays (x0, x1, ...)
var allX = new Array(n); // array of length n
for (var i=0; i<n; i++){
allX[i] = [x,y,z]; // array with elements x, y, z
}
now you can access e.g. the second array (x1
) like:
var x1 = allX[1];
or the third element of the third array (x2[2]
) like:
var z = allX[2][2];
Edit: see this explanation about the differences of array declaration between new Array()
and []
精彩评论