Created
January 29, 2017 10:06
-
-
Save SK-CSE/ceaaa2806fcab77cb836a521f4b2b618 to your computer and use it in GitHub Desktop.
mutidimention 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
// 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