1

I want to initialize and then print the elements of a 2D array using javascript. I wrote this code but nothing displays as output. How to output this array?

var m = 6;
var n = 3;
var mat = new Array[m][n];

for (i = 0; i < mat.length; i++) {
  for (j = 0; j < mat[i].length; j++) {
    mat[i][j]) = i * j;
    document.writeln(mat[i][j]);
  }
  document.writeln("<br />");
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Doen
  • 33
  • 1
  • 1
  • 6
  • 1
    Note, it's not necessary to initialize the array with its dimensions. You can do `var mat = [];` and still get the results you'd like, as long as you change your loops accordingly – Brennan Feb 11 '16 at 21:14

3 Answers3

1

As BenG pointed out, you've got an extra ) but you also aren't initializing your array correctly. Javascript doesn't allow you to declare multi-dimensional arrays like other languages. Instead, you'd have to do something more like this:

var m = 6;
var n = 3;
var mat = new Array(m);
for (var i = 0; i < m; i++) {
  mat[i] = new Array(n);
}
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
1

<html>
    <body>
    </body>
    <script>
        var m=6;
        var n=3;
        var mat =new Array(m);

        for( var i=0; i < m ; i++){

            mat[i] = new Array(n);

            for( var j=0;j< n ;j++){
                mat[i][j] = i*j;
                document.writeln(mat[i][j]);
            }

            document.writeln("<br />");
        }
    </script>
</html>
   
Z.Z.
  • 674
  • 6
  • 16
  • @Doen You are welcome. Here is good practice of [How to Create 2D Array in JavaScript](http://stackoverflow.com/a/966239/2802809) – Z.Z. Feb 11 '16 at 21:27
0

Javascript arrays are dynamic. They will grow to the size you require. You can call push() to add a new element to the array. It's also worth noting that you should avoid using the new keyword with objects and arrays. Use their literal notations [] for arrays and {} for objects. So a better solution here would be to push to the arrays as you need them.

var mat = [];
var m = 6;
var n = 3;
for (var i = 0; i < m; i++) {
  // Let's add an empty array to our main array
  mat.push([]);
  for (var j = 0; j < n; j++) {
    mat[i].push(i * j);
    document.writeln(i * j);
  }
  document.writeln('<br />');
}
Stewart
  • 3,023
  • 2
  • 24
  • 40