简体   繁体   中英

Initializing the 2D array elements in javascript

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 />");
}

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);
}

 <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> 

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 />');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM