简体   繁体   中英

Javascript - Looping through elements on the array, then next elements

I'd need to construct HTML table based arrays. I'm almost here but stuck in one point. Let me try to explain:

I already could construct the header of the table, with as many column as I need, OK

rowLength = 2 in my case, OK - > so I need to create two data rows

notUniq = 8 the full number of ma elements

arrayLength = 4, basically that is the table header column number.

Answers is an array, with 8 element: Adela Cervantsz,true,Dell,Good lapotp please,false,Barton Friesner,iOS please,IPad

So part of my code:

    for (var k = 0; k < rowLength; k++) {
            string += "<tr>";
            for (var j = 0; j < notUniq; j++) {
                string += "<td style=" + "width: 5%; font-size:70%" + ">" + Answers[j] + "</td>";
            }
            string += "</tr>";
        }

It produces me: Please click to check So it crates 2 rows, ok, but each row has 8 columns, not ok, I'd need just the first 4 element, then the 2nd 4 element.

If I modify the code, so if "for" with arrayLength 4 times, so the code is:

    for (var k = 0; k < rowLength; k++) {
            string += "<tr>";
            for (var j = 0; j < arrayLength; j++) {
                string += "<td style=" + "width: 5%; font-size:70%" + ">" + Answers[j] + "</td>";
            }
            string += "</tr>";
        }  

Then I get 2 rows, OK, 4 columns, OK, but both row has the same values :( Fors sure I'd need 1st row is the first 4 elements, the 2nd row is the next 4 elements.. Please click here to check the 2nd result

Could you help me on this? I gues I'd need modify / extend somehow the Answers[l] part, to get the first 4, then the next. Really appreciate any help! Thanks!

You must consider the row index in the Answers array. Each new row, the index must be increased by arrayLength. Answers[k*arrayLength + j] should do the trick

for (var k = 0; k < rowLength; k++) {
    string += "<tr>";
    for (var j = 0; j < arrayLength; j++) {
        string += "<td style=" + "width: 5%; font-size:70%" + ">" + Answers[k*arrayLength + j] + "</td>";
    }
    string += "</tr>";
} 

Try this below:

var length = i = 0;
for (var k = 0; k < rowLength; k++) {
     length+=arrayLength;
     string += "<tr>";
     for (var j = i; j < length; j++) {
          string += "<td style=" + "width: 5%; font-size:70%" + ">" + Answers[j] + "</td>";
     }
     string += "</tr>";
     i+=arrayLength;   
 }  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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