打印二维阵列的每个第一个元素

时间:2016-09-14 09:20:01

标签: javascript

我试图打印出每个数组的每个第一个元素,然后是索引上的下一个元素,这是我目前的进展......

var data = ['x', [1, 2, 3,4], ['a', 'b','c', 'd'], ['I', 'II', 'III', 'IV']];

for (var i = 1; i < data.length; i++) {
  for (var j = 0; j < 1; j++) {
    console.log(data[i][j]);  
  }
}

我的第一个结果是1aI,我怎样才能打印2bII,3cIII,4dIV

2 个答案:

答案 0 :(得分:1)

你的算法应该是这样的:

For each column:
   value = ""
   For each row: 
      combine value with the element
   print value

&#13;
&#13;
var data = ['x', [1, 2, 3,4], ['a', 'b','c', 'd'], ['I', 'II', 'III', 'IV']];

for (var j = 0; j < data[1].length; j++) {
  
  var value = "";
 
  for (var i = 1; i < data.length; i++) {
    value = value + data[i][j];  
  }
  
  console.log(value);
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

var data = ['x', [1, 2, 3,4], ['a', 'b','c', 'd'], ['I', 'II', 'III', 'IV']];
for (var i = 0; i < data.length; i++) {
   output = '';
   for (var j = 1; j < 4; j++) {
       output += data[j][i];
    }  
      console.log(output);
}