i want to init a two-dimensional dynamic array in javascript, it don't limit element (maybe) like
var dynamic = new Array ();
dynamic[] = new Array ();
after i want to add value to special array like
dynamic[id].push(2); // id = 3, dynamic[3][0] = 2
...
dynamic[id].push(3); // id = 3, dynamic[3][1] = 3
...
dynamic[id].push(5); // id = 5, dynamic[5][0] = 5
it's possible? How can i do that, thanks
One thing you could do is something like this (jsfiddle):
var dynamic = [];
dynamic.push = function (id, value) {
if (!this[id]) {
this[id] = [];
}
this[id].push(value);
}
dynamic.push(3, 2);
dynamic.push(3, 3);
dynamic.push(5, 5);
Of course, this can be done even better, but it gets the point across. Personally, I'd write a class for this.
Edit: Also, keep in mind that this creates an array with a high potential of having a whole lot of undefined
values, which needs to be taken care of when reading from it. Also, arrays with holes like this have bad performance (if this will be an issue -- for a few, even a few hundred, values, it won't matter).
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