简体   繁体   English

如何在 Java 脚本中打印以下多维数组?

[英]How to print the following Multi-Dimensional array in Java Script?

I have the following array (the code is written in Java):我有以下数组(代码是用 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 what I want to do is to print 111222 and I accomplished that in Java by doing this:我想做的是打印 111222,我通过这样做在 Java 中完成了它:

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 the equivalent of this in JavaScript?这在 JavaScript 中相当于什么?

Here is the equivalent code in Javascript (no space its not a script version of java) 这是Javascript中的等效代码(没有空格,它不是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]);
  }
}
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.) 虽然将所有字符串添加到一起并将它们打印为一个可以更聪明(可以添加到元素或提醒它。)

  • In javascript you can create multi dimensional array using single dimensional arrays. 在javascript中,您可以使用单维数组创建多维数组。
  • 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); 

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]);
    }
}
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: 输出: 在此输入图像描述

js is very powerfull; js很强大; just use spread operator只需使用传播运算符

 mat = [[1,2,3],[3,4,5]] mat.forEach(v=>console.log(...v));

// output run the code see the output. // output 运行代码见 output。
1 2 3 1 2 3
3 4 5 3 4 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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