You can create a simple wrapper to make the call convenient: http://jsfiddle.net/QRRXG/2/ .
A multidimensional array is just an array in another. Thus, you can build an array with 10 arrays, which, in turn, have 10 arrays each. Then get one with arr[i][j]
.
Elements can be represented as an object:
{ name: "foo", link: "bar" }
then such an element can be parsed as obj.name
and obj.link
.
var multi = (function() { var data = []; // initialize for(var i = 0; i < 10; i++) { data[i] = []; for(var j = 0; j < 10; j++) { data[i][j] = []; } } return { get: function(i, j) { // will return an array of items return data[i][j]; }, push: function(i, j, v) { // will add an item data[i][j].push(v); }, clear: function(i, j) { // will remove all items data[i][j] = []; }, iterateDefined: function(f) { for(var i = 0; i < 10; i++) { for(var j = 0; j < 10; j++) { if(data[i][j].length > 0) { f(data[i][j], i, j); } } } } }; })();
You can use it like:
multi.push(2, 3, { name: "foo", link: "test1" }); multi.push(2, 3, { name: "bar", link: "test2" }); multi.push(1, 4, { name: "haz", link: "test3" }); multi.push(5, 7, { name: "baz", link: "test4" }); multi.clear(5, 7); console.log(multi.get(2, 3)); // logs an array of 2 items console.log(multi.get(1, 4)); // logs an array of 1 item console.log(multi.get(5, 7)); // logs an array of 0 items console.log(multi.get(2, 3)[0].name); // logs "foo" console.log(multi.get(2, 3)[1].link); // logs "test2" multi.iterateDefined(function(items, i, j) { console.log(items, i, j); // will log two times });