How to print the following multidimensional array in Java Script?

I have the following array (code written in Java):

String[][] a = new String[3][2]; a[0][0] = "1"; a[0][1] = "2"; a[1][0] = "1"; a[1][1] = "2"; a[2][0] = "1"; a[2][1] = "2"; 

and I want to print 111222, and I did it in Java by doing the following:

 for (int i=0;i < a[i].length;i++){ for(int j=0;j <a.length;j++){ System.out.print(a[j][i]); } } 

What is equivalent to this in JavaScript?

+6
source share
5 answers

Here is the equivalent code in Javascript (without a space, this is not a version of the Java script)

! edit missing loop details, fixed now

 var a = []; a.push(["1", "2"]); a.push(["1", "2"]); a.push(["1", "2"]); for(var i = 0; i < a[i].length; i++) { for(var z = 0; z < a.length; z++) { console.log(a[z][i]); } } 
+8
source
 for (i=0; i < a.length; i++) { for (j = 0; j < a[i].length; j++) { document.write(a[i][j]); } } 

Although it would be wiser to add all the lines together and print them as one (you can add to the element or warn about it.)

+3
source
  • In JavaScript, you can create a multidimensional array using one-dimensional arrays.
  • For each element in the array, assign a different array to make it multidimensional.

  // first array equivalent to rows let a = new Array(3); // inner array equivalent to columns for(i=0; i<a.length; i++) { a[i] = new Array(2); } // now assign values a[0][0] = "1"; a[0][1] = "2"; a[1][0] = "1"; a[1][1] = "2"; a[2][0] = "1"; a[2][1] = "2"; /* console.log appends new line at end. So concatenate before printing */ let out=""; for(let i=0; i<a.length; i++) { for(let j=0; j<a[i].length; j++) { out = out + a[i][j]; } } console.log(out); 

+2
source
 var a = []; a[0] = []; a[0][0] = "1"; a[0][1] = "2"; a[1] = []; a[1][0] = "1"; a[1][1] = "2"; a[2] = []; a[2][0] = "1"; a[2][1] = "2"; for (i = 0; i < a[i].length; i++) { for (j = 0; j < a.length; j++) { document.write(a[j][i]); } } 
+1
source
 var arr =[ [1,2,3], [4,5,6], [7,8,9] ],arrText=''; for (var i = 0; i < arr.length; i++) { for (var j = 0; j < arr[i].length; j++) { arrText+=arr[i][j]+' '; } console.log(arrText); arrText=''; } 

Conclusion: enter image description here

0
source

Source: https://habr.com/ru/post/898617/


All Articles