Skip to content

Instantly share code, notes, and snippets.

@adriancooney
Created April 4, 2012 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adriancooney/2301237 to your computer and use it in GitHub Desktop.
Save adriancooney/2301237 to your computer and use it in GitHub Desktop.
Javascript 2D Array
/* Extremely simple definition of a 2D array in Javascript. Javascript doesn't allow for a match-all getter so a length has to be defined. This defines the height or rows of the array but not the width; the width or columns is as big as you want it to be, sugar. For some odd reason, the __defineGetter__ doesn't send the name of the current "get" to the callback (which is silly in my opinion for situations exactly like these) so I had to convert the functions to strings. */
var Array2D = function(l) {
if(!l) throw new Error("Please specify a length for your Array2D");
this.arr = [];
this.definedLength = l;
for(var i = 0; i < l; i++) {
this.__defineGetter__(i, Function("var i = " + i + ";if(!this.arr[i]) this.arr[i] = [];return this.arr[i];"));
}
this.__defineGetter__("length", function() {
return this.arr.length;
});
this.__defineGetter__("definedLength", function() {
return l;
});
return this;
};
Array2D.prototype.forEach = function(fn) {
var that = this;
this.arr.forEach(function(arr, y) {
arr.forEach(function(val, x) {
fn.call(that, val, x, y);
});
});
};
/** Example Usage **/
var arr = new Array2D(40);
arr[20][10] = 5;
arr[5][3] = 6;
arr.length; //Returns 2, counts the amount of rows set
arr.definedLength; //Returns 40
arr.forEach(function(value, column, row) {
//Yay
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment