Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - control two-dimensional dynamic array

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

like image 488
DeLe Avatar asked May 19 '13 10:05

DeLe


1 Answers

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).

like image 118
Ingo Bürk Avatar answered Sep 29 '22 09:09

Ingo Bürk