Skip to content

Instantly share code, notes, and snippets.

@jdelafon
Last active July 14, 2016 08:55
Show Gist options
  • Save jdelafon/6bf8b211b3c8db0a044ea365dd67cbd9 to your computer and use it in GitHub Desktop.
Save jdelafon/6bf8b211b3c8db0a044ea365dd67cbd9 to your computer and use it in GitHub Desktop.
Initialize a n-dimensional array in Javascript
/*
* Recursive function to initialize a n-dimensional array.
* @param *dims:
*/
function emptyArray(dims) {
var arr = new Array(dims || 0);
var i = dims;
if (arguments.length > 1) {
var args = Array.prototype.slice.call(arguments, 1);
while(i--) arr[dims-1 - i] = emptyArray.apply(this, args);
}
return arr;
}
emptyArray(); // [] or new Array()
emptyArray(2); // new Array(2)
emptyArray(3, 2); // [new Array(2),
// new Array(2),
// new Array(2)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment