Javascript 如何在 Java Script 中打印以下多维数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7652342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print the following Multi-Dimensional array in Java Script?
提问by Jimmy
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 中的 this 等价物是什么?
回答by megakorre
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]);
}
}
回答by Madara's Ghost
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.)
尽管将所有字符串添加在一起并将它们作为一个打印出来会更聪明(可以添加到元素或提醒它。)
回答by nadeem
- 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.
- 在javascript中,您可以使用一维数组创建多维数组。
- 对于数组中的每个元素,分配另一个数组以使其多维。
// 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);
回答by Christian
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]);
}
}