const m = 4;
const n = 5;
let arr = new Array(m); // create an empty array of length n
for (var i = 0; i < m; i++) {
arr[i] = new Array(n); // make each element an array
}
console.log(arr); // Output: [ [ <5 empty items> ], [ <5 empty items> ], [ <5 empty items> ], [ <5 empty items> ] ]
<script>
// Create one dimensional array
var gfg = new Array(2);
document.write("Creating 2D array <br>");
// Loop to create 2D array using 1D array
for (var i = 0; i < gfg.length; i++) {
gfg[i] = new Array(2);
}
var h = 0;
// Loop to initialize 2D array elements.
for (var i = 0; i < 2; i++) {
for (var j = 0; j < 2; j++) {
gfg[i][j] = h++;
}
}
// Loop to display the elements of 2D array.
for (var i = 0; i < 2; i++) {
for (var j = 0; j < 2; j++) {
document.write(gfg[i][j] + " ");
}
document.write("<br>");
}
</script>
<script>
// Create one dimensional array
var gfg = new Array(3);
// Loop to create 2D array using 1D array
document.write("Creating 2D array <br>");
for (var i = 0; i < gfg.length; i++) {
gfg[i] = [];
}
var h = 0;
var s = "GeeksforGeeks";
// Loop to initialize 2D array elements.
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
gfg[i][j] = s[h++];
}
}
// Loop to display the elements of 2D array.
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++)
{
document.write(gfg[i][j] + " ");
}
document.write("<br>");
}
</script>