Skip to content

Instantly share code, notes, and snippets.

@SK-CSE
Created January 29, 2017 10:06
Show Gist options
  • Save SK-CSE/ceaaa2806fcab77cb836a521f4b2b618 to your computer and use it in GitHub Desktop.
Save SK-CSE/ceaaa2806fcab77cb836a521f4b2b618 to your computer and use it in GitHub Desktop.
mutidimention array in javascript
// JavaScript arrays are only one-dimensional, but you can create multidimensional arrays by creating arrays of arrays.
Array.matrix = function(numrows, numcols, initial) {
var arr = [];
for (var i = 0; i < numrows; ++i) {
var columns = [];
for (var j = 0; j < numcols; ++j) {
columns[j] = initial;
}
arr[i] = columns;
}
return arr;
}
var nums = Array.matrix(6,6,0);
console.log(nums[1][1]); // displays 0
console.log(nums); /*[ [ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ] ] */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment