Last active
July 14, 2016 08:55
-
-
Save jdelafon/6bf8b211b3c8db0a044ea365dd67cbd9 to your computer and use it in GitHub Desktop.
Initialize a n-dimensional array in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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