i am trying to create multidimensional array…For right now I have this…
var a = []; // array of size 0
a[0] = [];
a[1] = []
Is there any better way to do this? I do not know the size of array until run time. So right now i know that I have 2 arrays of array but sometimes i will have more depending how many rows I pull out from database.
Note that // array of size 0 is correct, but is not a limiter. You dont need to know how big the array is going to be before constructing it.
If you dont know how many records there will be, then your loop will simply invoke a.push(newitem)
for each item.
I have function in PHP that does some work with database pulls out records based on query. Results of what query when printer with print_r function look like this…
I pass this array to JS external file. As you can see from above right now that array has 2 records but sometimes it might have 5 or 6 or whatever. Right now I am accessing this records like this…
I don’t know if there is a “best” way, but here is what I do.
var a = []; // no need to size initially; keep code small and fast-loading
var M, N; // number of rows and columns of array, respectively
If you could feed in values for M and N, that would be good. Saving them as their own variables might be handy for future use. Or you could calculate them on the fly. Personally, I like to avoid computing anything repeatedly, especially within loops, so once values are calculated I save them. Perhaps you could assign M = phpArray.length. N could also be computed at run-time. Either way, once you have values for the number of rows (M) and columns (N) of the array to be made, resize the array as needed.
for (var i = 0; i < M; ++i) { // Create M new arrays within the existing array
a[i] = [];
for (var j = 0; j < N; ++j) {
a[i][j] = value to be assigned;
}
}
Voila! That is one way to dynamically create a 2-dimensional array in JavaScript. All it takes is two loops.