多维数组以字符串与新行中的每个子数组

时间:2018-09-29 19:36:23

标签: arrays string

我正在尝试像这样转换多维数组:

var array = [["ID","Cue","Target","InitialCopyLen","InitialCopyStrict","NumStudied","NumTested","NumDropped","studyCountLen","testCountLen","studyCountStrict","testCountStrict","finaltestLen","finaltestStrict"],["bl","AGLUK","JAW","0","0","0","0","0","0","0","0","0","0","0"],["bl","AKI","MONEY","0","0","0","0","0","0","0","0","0","0","0"]];

类似这样(作为字符串):

ID  Cue Target  InitialCopyLen  InitialCopyStrict   NumStudied  NumTested   NumDropped  studyCountLen   testCountLen    studyCountStrict    testCountStrict finaltestLen    finaltestStrict
bl  AGLUK   JAW 0   0   0   0   0   0   0   0   0   0   0
bl  AKI MONEY   0   0   0   0   0   0   0   0   0   0   0

我尝试先转换为字符串,然后使用替换函数:

var newString = array.toString(array);
newString = newString.replace(/.{14}/g, '$&\n');

但是很明显,这仅适用于第14个字符,我需要每个第14个逗号。

然后我想到了这样的东西:

var i;
var commaCount = 0;
for (i = 0; i < newString.length; i++) {
    if (i == ","){
        commaCount++
       if (commaCount == "14"){
          // INSERT NEW LINE HERE    
       }
    }
} 

x.innerHTML = newString;

但是也许有更聪明的方法可以做到这一点?我基本上想将整个大数组转换成一个字符串,每个子数组都放在自己的行上。

2 个答案:

答案 0 :(得分:0)

尽管遍历内部数组中的每个元素,您仍可以使用for-each循环将数组的每个部分分别转换为String。

for(var element : array){
     str = element.toString();
     System.out.println(str);
     }

System.out.println()将处理“ \ n”

答案 1 :(得分:0)

我找到了答案:

array.forEach(function(element) {
        x.innerHTML += element + "<br>";
    });`