How to print the following Multi-Dimensional array in JavaScript?

后端 未结 5 1044
醉酒成梦
醉酒成梦 2021-01-05 01:49

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

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

a[1][0] = \"1\";  
a[1][1]          


        
相关标签:
5条回答
  • 2021-01-05 02:13
    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='';
            }
    

    Output:

    0 讨论(0)
  • 2021-01-05 02:14
    for (i=0; i < a.length; i++) {
       for (j = 0; j < a[i].length; j++) { document.write(a[i][j]); }
    }
    

    Though it would be smarter to add all the strings together and the print them out as one (could add to an element or alert it out.)

    0 讨论(0)
  • 2021-01-05 02:21
    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]);
        }
    }
    
    0 讨论(0)
  • 2021-01-05 02:26

    Here is the equivalent code in Javascript (no space its not a script version of java)

    ! edit missed the particulars of the loops, 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]);
      }
    }
    
    0 讨论(0)
  • 2021-01-05 02:28
    • In javascript you can create multi dimensional array using single dimensional arrays.
    • For every element in an array assign another array to make it multi dimensional.

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

    0 讨论(0)
提交回复
热议问题